Imports System.IO
Imports MySql.Data.MySqlClient

Public Class friendly_match

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

    Public _blue As friendly_fighter   ' Blue Fighter Information
    Public _red As friendly_fighter    ' Red Fighter Information
    Public _referee As person          ' Referee Information

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

    Private _match_id As Integer        ' Match Identification Number
    Private _max_rounds As Integer      ' Maximum Round Number
    Private _round_number As Integer    ' Round Number

    Private _matchTimer As match_timer  ' Timer For Playing The Rounds
    Private _matchBreak As match_timer  ' Timer For Having Break

    Private _max_differenace As Integer ' Max Difference In Score
    Private _enaMaxSdiff As Boolean     ' End Match When Difference Reached
    Private _enaSudenDth As Boolean     ' Enable Forth Round When Score Are Equal

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

    ReadOnly Property Round As Integer
        Get
            Return _round_number
        End Get
    End Property

    ReadOnly Property Time As match_timer
        Get
            Return _matchTimer
        End Get
    End Property

    ReadOnly Property Break As match_timer
        Get
            Return _matchBreak
        End Get
    End Property

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

    ' Incase you want to create instant match
    Public Sub New(Blue As Integer, Red As Integer, Referee As Integer, Rounds As Integer)

        ' Match Fighters
        _blue = New friendly_fighter(Blue)
        _red = New friendly_fighter(Red)

        ' Match Referee
        _referee = New person(Referee)

        ' Match Round Timer
        _matchTimer = New match_timer(My.Settings.match_round_time_minutes, My.Settings.match_round_time_seconds)

        ' Match Break Timer
        _matchBreak = New match_timer(My.Settings.match_break_time_minutes, My.Settings.match_break_time_seconds)

        ' Sudden Death Option
        _enaSudenDth = My.Settings.match_enable_sudden_death

        ' Max Score Difference Option
        _enaMaxSdiff = My.Settings.match_enable_max_difference

    End Sub

    '-----------------------------------------------------------------
    '   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 = " & _match_id & " 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
                        _blue = New friendly_fighter(RDR("blue_fighter"))
                    Catch ex As Exception
                        _blue = Nothing
                    End Try

                    Try
                        _red = New friendly_fighter(RDR("red_fighter"))
                    Catch ex As Exception
                        _red = 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` = " & _match_id & ";
        ")

        ' 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 _match_id = 0 Or _match_id = 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`	= " & _match_id & ";
        ")

        ' 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 _blue.Score > _red.Score Then
            WinnerID = _blue.Person.ID    ' Blue Fighter Wins
        ElseIf _blue.Score < _red.Score Then
            WinnerID = _red.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`	= " & _blue.Score & ",
                `blue_foul`		= " & _blue.Gamjum & ",
                `red_score`		= " & _red.Score & ",
                `red_foul`		= " & _red.Gamjum & ",
	            `winner`		= " & WinnerID & ",
                `ended`         = 1
            WHERE 
	            `emn`	= " & _match_id & ";
        ")

        ' 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`	= " & _blue.Score & ",
                `blue_foul`		= " & _blue.Gamjum & ",
                `red_score`		= " & _red.Score & ",
                `red_foul`		= " & _red.Gamjum & ",
                `winner`		= " & WinnerID & ",
                `notes`		    = '" & Note & "',
                `winnerBy`		= '" & WinnerBy & "',
                `ended`         = 1
            WHERE 
	            `emn`	= " & _match_id & ";
        ")

        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
