Imports System.IO
Imports MySql.Data.MySqlClient

Public Class match

    '--[MATCH FIGHTERS]---------------

    Public BlueFighter As fighter       ' Blue Fighter Information
    Public RedFighter As fighter        ' Red Fighter Information

    '--[MATCH REFEREE]----------------

    Public Referee As person            ' Referee Information

    '--[MATCH RECORD NUMBER]----------

    Private _eventID As Integer         ' Event Record Number & Also The Event Number
    Private _courtID As Integer         ' Court Record Number
    Private _matchID As Integer         ' Match Record Number

    '--[EVENT MATCH NUMBERS]----------

    Private _eventRound As Integer      ' Event Phase Number (Which Phase Is The Event Matches)
    Private _matchNumber As Integer     ' Match Event Round Match Number
    Private _courtNumber As Integer     ' Match Court Number

    '--[MATCH SETTINGS]---------------

    Private _maxRound As Integer        ' Max Number Of Rounds
    Private _maxRoundMin As Integer     ' Max Round Minutes
    Private _maxRoundSec As Integer     ' Max Round Sec
    Private _maxBreakMin As Integer     ' Max Break Minutes
    Private _maxBreakSec As Integer     ' Max Break Seconds
    Private _maxScoreDif As Integer     ' Max Score Difference
    Private _enaMaxSdiff As Boolean     ' End Match When Difference Reached
    Private _enaSudenDth As Boolean     ' Enable Forth Round When Score Are Equal

    '--[Display Numbers]--------------

    Private _RoundNum As Integer = 1    ' Round Number
    Private _RoundMin As Integer        ' Round Minutes
    Private _RoundSec As Integer        ' Round Seconds
    Private _BreakMin As Integer        ' Break Minutes
    Private _BreakSec As Integer        ' Break Seconds

    '--[CONSTRUCTORS]-------------------------------------------------

    ReadOnly Property ID As Integer
        Get
            Return _matchID
        End Get
    End Property

    ReadOnly Property COURT As Integer
        Get
            Return _courtID
        End Get
    End Property

    ReadOnly Property ROUND As Integer
        Get
            Return _RoundNum
        End Get
    End Property

    '--[CONSTRUCTORS]-------------------------------------------------

    ' Incase you have an event and its match number
    Public Sub New(EventID As Integer, MatchNumber As Integer)

        _eventID = EventID
        _matchID = MatchNumber
        GetMatchData()

    End Sub

    ' Incase you want to create instant match
    Public Sub New(BlueID As Integer, RedID As Integer, RefereeID As Integer)

        BlueFighter = New fighter(BlueID, _eventID, _matchID)
        RedFighter = New fighter(RedID, _eventID, _matchID)
        Referee = New person(RefereeID)

        SetDefault()
        ReTime_Round()
        ReTime_Break()

    End Sub

    '-----------------------------------------------------------------
    '   READING MATCH NUMBER
    '-----------------------------------------------------------------

    Private Sub SetDefault()

        _RoundNum = 1
        _maxRound = My.Settings.match_rounds
        _maxRoundMin = My.Settings.match_round_time_minutes
        _maxRoundSec = My.Settings.match_round_time_seconds
        _maxBreakMin = My.Settings.match_break_time_minutes
        _maxBreakSec = My.Settings.match_break_time_seconds
        _enaSudenDth = My.Settings.match_enable_sudden_death

    End Sub

    Private Sub ReTime_Round()
        _RoundMin = _maxRoundMin
        _RoundSec = _maxRoundSec
    End Sub

    Private Sub ReTime_Break()
        _BreakMin = _maxBreakMin
        _BreakSec = _maxBreakSec
    End Sub

    Public Function Time_CountDown() As Boolean

        If _RoundMin > 0 Then

            If _RoundSec > 0 And _RoundSec < 60 Then
                _RoundSec -= 1
                Return False
            Else
                _RoundMin -= 1
                _RoundSec = 59
                Return False
            End If

        Else

            If _RoundSec > 0 And _RoundSec < 60 Then
                _RoundSec -= 1
                Return False
            Else
                _RoundSec = 59
                Return True
            End If

        End If

    End Function

    '-----------------------------------------------------------------
    '   READING MATCH NUMBER
    '-----------------------------------------------------------------

    ' THIS FUNCTION GETS THE NEWLY CREATED MATCH NUMBER

    Private Sub GetMatchData()

        Dim QRY As String = "SELECT ecn, ern, emn, blue_fighter, red_fighter FROM test.event_matches where emn = " & _matchID & " and started = 0 and ended = 0 and (not isnull(red_fighter)) and (not isnull(blue_fighter)) order by ern, emn asc"
        Dim CON As New MySqlConnection(CON_STRING)
        Dim COM As New MySqlCommand(QRY, CON)
        Dim RDR As MySqlDataReader

        Try
            CON.Open()
            RDR = COM.ExecuteReader
            If RDR.HasRows = True Then
                While RDR.Read

                    Try
                        _courtID = RDR("ecn")
                    Catch ex As Exception
                        _courtID = 0
                    End Try

                    Try
                        _eventRound = RDR("ern")
                    Catch ex As Exception
                        _eventRound = 0
                    End Try

                    Try
                        BlueFighter = New fighter(RDR("blue_fighter"), _eventID, _matchID)
                    Catch ex As Exception
                        BlueFighter = Nothing
                    End Try

                    Try
                        RedFighter = New fighter(RDR("red_fighter"), _eventID, _matchID)
                    Catch ex As Exception
                        RedFighter = Nothing
                    End Try


                End While
            End If
            CON.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            CON.Dispose()
        End Try

    End Sub

    ' THIS FUNCTION RETURNS AVAILABLE NUMBER FOR A NEW MATCH

    Private Function GetAvailableNewMatchID() As Integer

        ' Select the Unstarted Matches From The Match Sequence
        Dim QRY As String = ("
			select
	            person.id as 'pid',
	            person.fname,
                person.mname,
                person.lname,
                TIMESTAMPDIFF(YEAR, person.date_of_birth, CURDATE()) as 'age',
                person.date_of_birth,
                person.category,
                person.weight,
                person.weight_class,
	            person.gender,
                person.picture,
                clubs.title as 'club',
                clubs.logo as 'logo',
                countries.iso3 as 'country',
                countries.flatflag as 'flag'
            FROM 
	            person
            left join
	            clubs on person.club = clubs.id
            left join 
	            countries on person.country = countries.id 
            where 
	            person.id=1
        ")

        Dim CON As New MySqlConnection(CON_STRING)
        Dim COM As New MySqlCommand(QRY, CON)
        Dim RDR As MySqlDataReader
        Dim NUM As Integer

        Try
            CON.Open()
            RDR = COM.ExecuteReader
            If RDR.HasRows = True Then
                While RDR.Read
                    Try
                        NUM = RDR("ID")
                    Catch ex As Exception

                    End Try
                End While
            End If
            CON.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            CON.Dispose()
        End Try

        Return NUM

    End Function

    Public Sub StartMatch()

        ' Update The Table With The Winner ID
        Dim QRY As String = ("
            SET SQL_SAFE_UPDATES = 0;

            UPDATE 
	            `event_matches` 
            SET
                `started` = 1
            WHERE 
	            `emn` = " & _matchID & ";
        ")

        ' Executing The Command
        Dim CON As New MySqlConnection(CON_STRING)
        Dim COM As New MySqlCommand(QRY, CON)

        Try
            CON.Open()
            COM.ExecuteNonQuery()
            CON.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            CON.Dispose()
        End Try

    End Sub

    Public Sub EndMatch()

        ' Testing This Condition
        If _matchID = 0 Or _matchID = Nothing Then Exit Sub

        ' Update The Table With The Winner ID
        Dim QRY As String = ("
            SET SQL_SAFE_UPDATES = 0;

            UPDATE 
	            `event_matches` 
            SET
                `ended`         = 1
            WHERE 
	            `emn`	= " & _matchID & ";
        ")

        ' Executing The Command
        Dim CON As New MySqlConnection(CON_STRING)
        Dim COM As New MySqlCommand(QRY, CON)

        Try
            CON.Open()
            COM.ExecuteNonQuery()
            CON.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            CON.Dispose()
        End Try

    End Sub

    '-----------------------------------------------------------------
    '   METHODES OF ENDING A MATCH
    '-----------------------------------------------------------------

    ' THIS SUB ENDS THE MATCH AUTOMATICALLY BY CALCULATING THE POINTS
    Private Sub AutoEndMatch()

        ' Winner ID Holder
        Dim WinnerID As Integer

        ' This Is Where We Do Decision Making
        If BlueFighter.Score > RedFighter.Score Then
            WinnerID = BlueFighter.Person.ID    ' Blue Fighter Wins
        ElseIf BlueFighter.Score < RedFighter.Score Then
            WinnerID = RedFighter.Person.ID     ' Red Fighter Wins
        End If

        ' Update The Table With The Winner ID
        Dim QRY As String = ("
            SET SQL_SAFE_UPDATES = 0;

            UPDATE 
	            `event_matches` 
            SET
                `blue_score`	= " & BlueFighter.Score & ",
                `blue_foul`		= " & BlueFighter.Gamjum & ",
                `red_score`		= " & RedFighter.Score & ",
                `red_foul`		= " & RedFighter.Gamjum & ",
	            `winner`		= " & WinnerID & ",
                `ended`         = 1
            WHERE 
	            `emn`	= " & _matchID & ";
        ")

        ' Executing The Command
        Dim CON As New MySqlConnection(CON_STRING)
        Dim COM As New MySqlCommand(QRY, CON)

        Try
            CON.Open()
            COM.ExecuteNonQuery()
            CON.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            CON.Dispose()
        End Try

    End Sub

    ' THIS SUB ENDS THE MATCH MANUALLY BY THE MAIN REFEREE IF NEEDED TO
    Private Sub ManualEndMatch(WinnerID As Integer, WinnerBy As String, Note As String)

        ' Update The Table With The Winner ID
        Dim QRY As String = ("
            SET SQL_SAFE_UPDATES = 0;

            UPDATE 
	            `event_matches` 
            SET
                `blue_score`	= " & BlueFighter.Score & ",
                `blue_foul`		= " & BlueFighter.Gamjum & ",
                `red_score`		= " & RedFighter.Score & ",
                `red_foul`		= " & RedFighter.Gamjum & ",
                `winner`		= " & WinnerID & ",
                `notes`		    = '" & Note & "',
                `winnerBy`		= '" & WinnerBy & "',
                `ended`         = 1
            WHERE 
	            `emn`	= " & _matchID & ";
        ")

        Dim CON As New MySqlConnection(CON_STRING)
        Dim COM As New MySqlCommand(QRY, CON)

        Try
            CON.Open()
            COM.ExecuteNonQuery()
            CON.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            CON.Dispose()
        End Try

    End Sub


End Class
