Imports System.ComponentModel
Imports System.IO
Imports MySql.Data.MySqlClient
Public Class frm_fighter_statistics
    Private Sub frm_fighter_statistics_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Me.Text = SelectedEvent.Title

        Try
            list_fighters("", SelectedEvent.ID)
        Catch ex As Exception

        End Try

    End Sub

    Private Sub Load_Fighter_Data(FighterID As Integer)

        Dim person As New person(FighterID)

        lbl_age.Text = person.Age.Years
        lbl_gender.Text = person.Gender
        lbl_name.Text = person.FullName
        lbl_nationality.Text = person.Nationality.Name
        lbl_last_weight.Text = person.Weight.Weight & "Kg"
        lbl_category.Text = person.Weight.WeightCategory
        lbl_weight_class.Text = person.Weight.WeightClass

        Try
            pb_fighter.Image = Image.FromStream(person.PICTURE)
        Catch ex As Exception
            pb_fighter.Image = Nothing
        End Try

        Try
            pb_flag.Image = Image.FromStream(person.Team.Country.Flag)
        Catch ex As Exception
            pb_flag.Image = Nothing
        End Try

    End Sub

    Private Sub Load_Fighter_Matches(FighterID As Integer, EventID As Integer)

        Dim QRY As String = ("

            /*-----------------------------------------------------
	            THIS CODE IS FOR SEARCHING THE MATCHES
                FOR A FIGHTER BY HIS/HER ID NUMBER
            -----------------------------------------------------*/

            SELECT
                event_matches.id as 'MatchID',
	            event_matches.emn as 'MatchNo',
                event_matches.ern as 'EventRound',
                if(" & FighterID & " = blue.id, concat(red.fname, ' ', if(isnull(red.mname), '', red.mname), ' ', red.lname), concat(blue.fname, ' ', if(isnull(blue.mname), '', blue.mname), ' ', blue.lname)) as 'Opponent',
                if(" & FighterID & " = winner.id, 'WIN', 'LOSE') as 'Result'
            FROM 
	            event_matches
            LEFT JOIN 
	            person as winner ON winner.id = event_matches.winner
            LEFT JOIN 
	            clubs as winner_club ON winner_club.id = winner.club
            LEFT JOIN 
	            person as blue ON blue.id = event_matches.blue_fighter
            LEFT JOIN 
	            clubs as blue_club ON blue_club.id = blue.club
            LEFT JOIN 
	            person as red ON red.id = event_matches.red_fighter
            LEFT JOIN 
	            clubs as red_club ON red_club.id = red.club

            Where
	            (blue_fighter = " & FighterID & " or red_fighter = " & FighterID & ")
                and
                event_matches.started = true 
                and 
                event_matches.ended = true
                and
                event_matches.eid = " & EventID & "
            order by
                ern,
                emn
	            asc
        ")

        Dim CON As New MySqlConnection(CON_STRING)
        Dim COM As New MySqlCommand(QRY, CON)
        Dim RDR As MySqlDataReader
        Dim LST As New List(Of dataset)

        Try
            CON.Open()
            RDR = COM.ExecuteReader
            If RDR.HasRows = True Then
                While RDR.Read
                    Dim MatchDisplayText As String = "Match No. " & Zero(RDR("MatchNo")) & ", Round " & RDR("EventRound") & ", " & RDR("Opponent") & " - " & RDR("Result")
                    LST.Add(New dataset(RDR("MatchID"), MatchDisplayText))
                End While
            End If
            CON.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            CON.Dispose()
        End Try

        lst_matches.DataSource = LST
        lst_matches.ValueMember = "ID"
        lst_matches.DisplayMember = "name"

    End Sub

    Private Sub Load_Fighter_Points(FighterID As Integer, EventID As Integer)

        Dim QRY As String = ("

            /*-----------------------------------------------------
	            THIS CODE IS FOR SEARCHING THE MATCH
                DATA OF WINS LOSSES AND COLLECTED POINTS
            -----------------------------------------------------*/

            Select
                (select count(*) as WIN from event_matches inner join event on event_matches.eid = event.id where event_matches.eid = " & EventID & " And event_matches.started = true And event_matches.ended = true And (blue_fighter = " & FighterID & " Or red_fighter = " & FighterID & ") And winner = " & FighterID & ") as 'WIN',
                (select count(*) as WIN from event_matches inner join event on event_matches.eid = event.id where event_matches.eid = " & EventID & " And event_matches.started = true And event_matches.ended = true And (blue_fighter = " & FighterID & " Or red_fighter = " & FighterID & ") And winner != " & FighterID & ") as 'LOSS',
                (select count(*) as WIN from event_matches inner join event on event_matches.eid = event.id where event_matches.eid = " & EventID & " And event_matches.started = true And event_matches.ended = true And (blue_fighter = " & FighterID & " Or red_fighter = " & FighterID & ") And winner = " & FighterID & ") * 3 as 'POINTS'
        ")

        Dim CON As New MySqlConnection(CON_STRING)
        Dim COM As New MySqlCommand(QRY, CON)
        Dim RDR As MySqlDataReader
        Dim LST As New List(Of dataset)

        Try
            CON.Open()
            RDR = COM.ExecuteReader
            If RDR.HasRows = True Then
                While RDR.Read
                    lbl_wins.Text = RDR("WIN")
                    lbl_loss.Text = RDR("LOSS")
                    lbl_rank.Text = RDR("POINTS")
                End While
            End If
            CON.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            CON.Dispose()
        End Try

    End Sub

    Private Sub Load_Match_Data(MatchID As Integer)

        Dim QRY As String = ("

            /*-----------------------------------------------------
	            THIS CODE IS FOR SEARCHING THE MATCH
                BY MATCH ID NUMBER
            -----------------------------------------------------*/

            SELECT
	            event_matches.id as 'MatchID',
                event_matches.ecn as 'Court',
	            event_matches.emn as 'MatchNo',
                event_matches.ern as 'EventRound',
	            concat(blue.fname, ' ', blue.mname, ' ', blue.lname) as 'BlueName',
	            blue_club.title as 'BlueClub',
                blue_club.logo as 'BlueLogo',
	            blue_score as 'BlueScore',
	            blue_foul as 'BlueFoul',
	            concat(red.fname, ' ', red.mname, ' ', red.lname) as 'RedName',
	            red_club.title as 'RedClub',
                red_club.logo as 'RedLogo',
	            red_score as 'RedScore',
	            red_foul as 'RedFoul',
                concat(winner.fname, ' ', winner.mname, ' ', winner.lname) as 'Winner'
            FROM 
	            event_matches
            LEFT JOIN 
	            person as winner ON winner.id = event_matches.winner
            LEFT JOIN 
	            clubs as winner_club ON winner_club.id = winner.club
            LEFT JOIN 
	            person as blue ON blue.id = event_matches.blue_fighter
            LEFT JOIN 
	            clubs as blue_club ON blue_club.id = blue.club
            LEFT JOIN 
	            person as red ON red.id = event_matches.red_fighter
            LEFT JOIN 
	            clubs as red_club ON red_club.id = red.club

            Where
                event_matches.started = true 
                and 
                event_matches.ended = true
                and
                event_matches.id = " & MatchID & "
            order by
                ern,
                emn
	            asc
        ")

        Dim CON As New MySqlConnection(CON_STRING)
        Dim COM As New MySqlCommand(QRY, CON)
        Dim RDR As MySqlDataReader
        Dim LST As New List(Of dataset)

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

                    Try
                        lbl_match_number.Text = RDR("MatchNo")
                    Catch ex As Exception

                    End Try

                    Try
                        lbl_court_number.Text = RDR("Court")
                    Catch ex As Exception

                    End Try

                    Try
                        lbl_blue_fighter.Text = RDR("BlueName")
                    Catch ex As Exception

                    End Try

                    Try
                        lbl_blue_score.Text = RDR("BlueScore")
                    Catch ex As Exception

                    End Try

                    Try
                        Dim data As Byte() = DirectCast(RDR("bluelogo"), Byte())
                        Dim BlueLogo = New System.IO.MemoryStream(data)
                        pb_blue_logo.Image = Image.FromStream(BlueLogo)
                    Catch ex As Exception
                        pb_blue_logo.Image = Nothing
                    End Try

                    Try
                        lbl_red_fighter.Text = RDR("RedName")
                    Catch ex As Exception

                    End Try

                    Try
                        lbl_red_score.Text = RDR("RedScore")
                    Catch ex As Exception

                    End Try

                    Try
                        Dim data As Byte() = DirectCast(RDR("redlogo"), Byte())
                        Dim RedLogo = New System.IO.MemoryStream(data)
                        pb_red_logo.Image = Image.FromStream(RedLogo)
                    Catch ex As Exception
                        pb_red_logo.Image = Nothing
                    End Try

                    Try
                        lbl_winner.Text = RDR("Winner")
                    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

    End Sub

    Public Sub ClearList()

        Try
            lst_fighters.DataSource = Nothing
            lst_fighters.Items.Clear()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub txt_search_TextChanged(sender As Object, e As EventArgs) Handles txt_search.TextChanged

        ClearList()

        Try
            list_fighters(txt_search.Text, SelectedEvent.ID)
        Catch ex As Exception

        End Try


    End Sub

    Private Sub lst_fighters_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lst_fighters.SelectedIndexChanged

        Try
            Load_Fighter_Data(lst_fighters.SelectedValue)
            Load_Fighter_Matches(lst_fighters.SelectedValue, SelectedEvent.ID)
            Load_Fighter_Points(lst_fighters.SelectedValue, SelectedEvent.ID)
        Catch ex As Exception

        End Try

    End Sub

    Private Sub btn_close_Click(sender As Object, e As EventArgs) Handles btn_close.Click

        Me.Close()

    End Sub

    Private Sub frm_fighter_statistics_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing

        'frm_main.Show()
        frm_event_control.Show()

    End Sub

    Private Sub pb_fighter_Click(sender As Object, e As EventArgs) Handles pb_fighter.Click

        If IsNothing(pb_fighter.Image) Then

            ' Open Picture File
            open_picture_file()

            ' Store The Picture
            update_fighter_picture()

        ElseIf Not IsNothing(pb_fighter.Image) Then

            Dim iPictureUpdate As DialogResult = MessageBox.Show("Would You Like To Update The Players Picture ?", "Picture Update", MessageBoxButtons.YesNo, MessageBoxIcon.Question)

            If iPictureUpdate = DialogResult.Yes Then

                ' Open Picture File
                open_picture_file()

                ' Store The Picture
                update_fighter_picture()

            End If

        End If

    End Sub

    Private Sub open_picture_file()

        'Creating A New Dialog
        Dim OpenPictureFile As New OpenFileDialog

        'Filtering The Types
        OpenPictureFile.Filter = "Image Files | *.jpg; *.jpeg; *.bmp; *.png; *.gif;"

        'Openning The File
        If OpenPictureFile.ShowDialog = System.Windows.Forms.DialogResult.OK Then

            Try
                ' Getting File Path
                Dim FilePath As String = OpenPictureFile.FileName()
                Dim FileName As String = System.IO.Path.GetFileName(OpenPictureFile.FileName)

                ' Picture File
                Dim Picture As New MemoryStream

                ' Define New Image Size
                Dim LogoSize As New Size(385, 500)

                ' Resizing The Image
                Dim ResizedImage = New Bitmap(Image.FromFile(FilePath), LogoSize)

                ' Display The Image
                pb_fighter.Image = ResizedImage

                ' Saving The Image As PNG Format
                pb_fighter.Image.Save(Picture, System.Drawing.Imaging.ImageFormat.Png)

                ' Read The Image As Bytes
                Dim arrImage() As Byte = Picture.GetBuffer

                ' Closing The Picture
                Picture.Close()

            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End If

    End Sub

    Private Sub update_fighter_picture()

        ' Query To Update
        Dim QRY As String = "update person set picture = @picture where id=" & lst_fighters.SelectedValue

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

        ' Preparing The Image
        Dim Picture As New MemoryStream
        pb_fighter.Image.Save(Picture, System.Drawing.Imaging.ImageFormat.Png)
        Dim arrImage() As Byte = Picture.GetBuffer
        Picture.Close()

        Try
            CON.Open()
            COM.Parameters.AddWithValue("@picture", arrImage)
            COM.ExecuteNonQuery()
            CON.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            CON.Dispose()
        End Try

    End Sub

    Public Function Zero(Number As Integer) As String

        If Number >= 0 And Number < 10 Then

            Return "00" & Number

        ElseIf Number >= 10 And Number < 100 Then

            Return "0" & Number

        Else

            Return Number

        End If

    End Function

    Private Sub list_fighters(filter As String, eventID As Integer)

        Dim QRY As String = ("

            select 
	            distinct
	            person.id, concat(person.fname, if(isnull(person.mname), '', concat(' ', person.mname)), ' ', person.lname) as name 
            from 
	            person
            left join
	            event_matches on (person.id = coalesce(event_matches.blue_fighter, 0) or person.id = coalesce(event_matches.red_fighter, 0))
            where 
	            concat(fname, if(isnull(mname), '', concat(' ', mname)), ' ', lname) like '%" & filter & "%'
                and
                event_matches.eid = " & eventID & "
            order by 
                fname, 
                mname, 
                lname 
                asc
        ")

        Dim CON As New MySqlConnection(CON_STRING)
        Dim COM As New MySqlCommand(QRY, CON)
        Dim RDR As MySqlDataReader
        Dim LST As New List(Of dataset)

        Try
            CON.Open()
            RDR = COM.ExecuteReader
            If RDR.HasRows = True Then
                While RDR.Read
                    LST.Add(New dataset(RDR("id"), RDR("name")))
                End While
            End If
            CON.Close()
        Catch ex As MySqlException
            MessageBox.Show(ex.Message)
        Finally
            CON.Dispose()
        End Try

        lst_fighters.DataSource = LST
        lst_fighters.ValueMember = "ID"
        lst_fighters.DisplayMember = "name"

    End Sub

    Private Sub lst_matches_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lst_matches.SelectedIndexChanged

        Try
            Load_Match_Data(lst_matches.SelectedValue)
        Catch ex As Exception

        End Try

    End Sub

End Class