using DevExpress.XtraEditors;
using DevExpress.XtraEditors.ColorPick.Picker;
using lol_coder.Log;
using LolDataRequestLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace lol_coder.Forms.Frame
{
    public partial class ResultFrame : UserControl
    {
        MainForm mainForm;
        public ResultFrame(MainForm _mainForm)
        {
            InitializeComponent();

            mainForm = _mainForm;
        }


        public void AllClear()
        {
            cmbRefresh();

            foreach (Control v in groupControl21.Controls)
            {
                if (v.GetType().ToString().Contains("TextEdit"))
                {
                    ((TextEdit)v).Text = "";
                }
            }
        }
        public void cmbRefresh()
        {
            try
            {
                cmbPOG.Properties.Items.Clear();

                for (int i = 0; i < 5; i++)
                {
                    string champ = mainForm.DC.BlueLiner.GetLiner(i).champ;
                    string champKor = "";

                    foreach (var v in DataManager.getInstance().mChampionTable)
                    {
                        if (v.Value.champNameENG.Equals(champ))
                        {
                            champKor = v.Value.champNameKOR;
                            break;
                        }
                    }

                    cmbPOG.Properties.Items.Add(champKor);
                }
                for (int i = 0; i < 5; i++)
                {
                    string champ = mainForm.DC.RedLiner.GetLiner(i).champ;
                    string champKor = "";

                    foreach (var v in DataManager.getInstance().mChampionTable)
                    {
                        if (v.Value.champNameENG.Equals(champ))
                        {
                            champKor = v.Value.champNameKOR;
                            break;
                        }
                    }

                    cmbPOG.Properties.Items.Add(champKor);
                }
            }
            catch(Exception ex) { }
            
        }

        private void btnPost_Click(object sender, EventArgs e)
        {
            try
            {
                cmbPOG.Properties.Items.Clear();
                for (int i = 0; i < 5; i++)
                {
                    string champ = mainForm.DC.BlueLiner.GetLiner(i).champ;
                    string champKor = "";

                    foreach (var v in DataManager.getInstance().mChampionTable)
                    {
                        if (v.Value.champNameENG.Equals(champ))
                        {
                            champKor = v.Value.champNameKOR;
                            break;
                        }
                    }

                    cmbPOG.Properties.Items.Add(champKor);
                }
                for (int i = 0; i < 5; i++)
                {
                    string champ = mainForm.DC.RedLiner.GetLiner(i).champ;
                    string champKor = "";

                    foreach (var v in DataManager.getInstance().mChampionTable)
                    {
                        if (v.Value.champNameENG.Equals(champ))
                        {
                            champKor = v.Value.champNameKOR;
                            break;
                        }
                    }

                    cmbPOG.Properties.Items.Add(champKor);
                }
            }
            catch (Exception ex)
            {

            }


       
             
            try
            {
                if (mainForm.MainLayerButton((SimpleButton)sender))
                {
                    mainForm.liveCoderFrame.AllOut();

                    DataSet 가져온데이터셋 = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.경기종료정보);

                    DataTable[] dts = new DataTable[8];
                    dts[0] = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.골드차이팀).Tables[0];
                    dts[1] = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.현재데미지량선수).Tables[0];
                    dts[2] = 가져온데이터셋.Tables[DBDefine.요청데이터분류.경기종료정보.GetStringValue()];
                    dts[3] = 가져온데이터셋.Tables[DBDefine.요청데이터분류.킬뎃어시.GetStringValue()];
                    dts[4] = 가져온데이터셋.Tables[DBDefine.요청데이터분류.타워철거전체.GetStringValue()];
                    dts[5] = 가져온데이터셋.Tables[DBDefine.요청데이터분류.오브젝트킬.GetStringValue()];
                    dts[6] = 가져온데이터셋.Tables[DBDefine.요청데이터분류.밴데이터.GetStringValue()];
                    dts[7] = 가져온데이터셋.Tables[DBDefine.요청데이터분류.골드차이팀.GetStringValue()];
                    
                    if (chkManualResult.Checked)
                    {
                        DataTable dt = new DataTable();
                        dt.Columns.Add("승리팀");
                        dt.Columns.Add("시간");
                        string 승리팀 = "블루";
                        string time = "0";
                        if (WinGroup.SelectedIndex != 0) 승리팀 = "레드";
                        time = (Convert.ToInt32(mTime.Text) * 60 + Convert.ToInt32(sTime.Text)).ToString();

                        dt.Rows.Add(new string[] { 승리팀, time });
                        dts[2] = dt;

                        dts[3] = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.킬뎃어시).Tables[0];
                        dts[4] = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.타워철거전체).Tables[0]; 
                        dts[5] = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.오브젝트킬).Tables[0];
                        dts[6] = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.밴데이터).Tables[0]; 
                        dts[7] = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.골드차이팀).Tables[0];
                    }
                    else
                    {
                        if (dts[2] == null)
                        {
                            MessageBox.Show("경기 종료 정보를 수신하지 못했습니다.");
                            mainForm.MainLayerButton(null);
                            return;
                        }
                    }
                    


                    string[] scores = new string[] { mainForm.bscore.Text, mainForm.rscore.Text, mainForm.bscoreAll.Text, mainForm.rscoreAll.Text };


                    mainForm.GoldGraph(false);
                    mainForm.TM.DisplayPost(dts, mainForm.DC, mainForm.GetTitle(), scores, chkT1Home.Checked, lblWinColor.BackColor, lblLossColor.BackColor, lblBlueColor.BackColor, lblRedColor.BackColor,chkKDA수동.Checked, txtKDABlue.Text, txtKDARed.Text);
                }                    
            }
            catch (Exception ex)
            {
                mainForm.Log(MethodBase.GetCurrentMethod().Name + " : " + ex.Message, LogWriter.LogType.Error);
            }
        }

        bool isPOGBlue = false;
        private void cmbPOG_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.팟지).Tables[0];

                dataGridView1.DataSource = dt;

                string champName = cmbPOG.SelectedItem.ToString();
                string champNameEng = "";
                txt1.Text = ""; txt2.Text = ""; txt3.Text = ""; txt4.Text = "";
                txt5.Text = ""; txt6.Text = ""; txt7.Text = ""; txt8.Text = "";

                foreach (var v in DataManager.getInstance().mChampionTable)
                {
                    if (v.Value.champNameKOR.Equals(champName))
                    {
                        champNameEng = v.Value.champNameENG;
                        break;
                    }
                }

                lblChampEng.Text = champNameEng;
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr[3].Equals(champNameEng))
                    {
                        txt9.Text = "";
                        d9.Text = "";

                        txt1.Text = "";
                        //K/D/A
                        if (dr[4].ToString() == "") dr[4] = "0";
                        if (dr[5].ToString() == "") dr[5] = "0";
                        if (dr[6].ToString() == "") dr[6] = "0";
                        txt2.Text = dr[4] + "/" + dr[5] + "/" + dr[6];
                        //분당 대미지 (11) 
                        try
                        {
                            txt3.Text = Convert.ToDouble(dr[11]).ToString("##0");
                        }
                        catch(Exception ex)
                        {
                            txt3.Text = "Err";
                        } 
                        
                        //KP (킬 관여율)
                        try
                        {
                            txt4.Text = Convert.ToDouble(dr[25]).ToString("##0.0") + "%";
                        }
                        catch(Exception ex)
                        {
                            txt4.Text = "Err";
                        }

                        //CS (크랩스코어)
                        try
                        {
                            txt5.Text = Convert.ToDouble(dr[15]).ToString("##0");
                        }
                        catch (Exception ex) { txt5.Text = "Err"; }

                        //DMG% (팀내 대미지 비중)
                        try { txt6.Text = Convert.ToDouble(dr[27]).ToString("##0.0") + "%"; }
                        catch (Exception ex) { txt6.Text = "Err"; }
                        //DMG/GOLD (골드당 대미지)
                        try { txt7.Text = (Convert.ToDouble(dr[26]) * 100).ToString("##0.0") + "%"; }
                        catch (Exception ex) { txt7.Text = "Err"; }
                        //CC SCORE (군중제어점수)
                        try { txt8.Text = Convert.ToDouble(dr[23]).ToString("##0"); }
                        catch (Exception ex) { txt8.Text = "Err"; }
                     
                    }
                }

                //팀, 라인, 선수명
                string[] strs = new string[3];
                if (mainForm.DC.BlueLiner.Top.champ.Equals(champNameEng)) { strs = new string[] { mainForm.DC.BlueLiner.TeamName, "TOP", mainForm.DC.BlueLiner.Top.Name }; isPOGBlue = true; }
                else if (mainForm.DC.BlueLiner.Jungle.champ.Equals(champNameEng)) { strs = new string[] { mainForm.DC.BlueLiner.TeamName, "JGL", mainForm.DC.BlueLiner.Jungle.Name }; isPOGBlue = true; }
                else if (mainForm.DC.BlueLiner.Mid.champ.Equals(champNameEng)) { strs = new string[] { mainForm.DC.BlueLiner.TeamName, "MID", mainForm.DC.BlueLiner.Mid.Name }; isPOGBlue = true; }
                else if (mainForm.DC.BlueLiner.ADCarry.champ.Equals(champNameEng)) { strs = new string[] { mainForm.DC.BlueLiner.TeamName, "BOT", mainForm.DC.BlueLiner.ADCarry.Name }; isPOGBlue = true; }
                else if (mainForm.DC.BlueLiner.Supporter.champ.Equals(champNameEng)) { strs = new string[] { mainForm.DC.BlueLiner.TeamName, "SPT", mainForm.DC.BlueLiner.Supporter.Name }; isPOGBlue = true; }

                else if (mainForm.DC.RedLiner.Top.champ.Equals(champNameEng)) { strs = new string[] { mainForm.DC.RedLiner.TeamName, "TOP", mainForm.DC.RedLiner.Top.Name }; isPOGBlue = false; }
                else if (mainForm.DC.RedLiner.Jungle.champ.Equals(champNameEng)) { strs = new string[] { mainForm.DC.RedLiner.TeamName, "JGL", mainForm.DC.RedLiner.Jungle.Name }; isPOGBlue = false; }
                else if (mainForm.DC.RedLiner.Mid.champ.Equals(champNameEng)) { strs = new string[] { mainForm.DC.RedLiner.TeamName, "MID", mainForm.DC.RedLiner.Mid.Name }; isPOGBlue = false; }
                else if (mainForm.DC.RedLiner.ADCarry.champ.Equals(champNameEng)) { strs = new string[] { mainForm.DC.RedLiner.TeamName, "BOT", mainForm.DC.RedLiner.ADCarry.Name }; isPOGBlue = false; }
                else if (mainForm.DC.RedLiner.Supporter.champ.Equals(champNameEng)) { strs = new string[] { mainForm.DC.RedLiner.TeamName, "SPT", mainForm.DC.RedLiner.Supporter.Name }; isPOGBlue = false; }

                cmbTeam.Properties.Items.Clear();
                cmbTeam.Properties.Items.Add(mainForm.DC.BlueLiner.TeamName);
                cmbTeam.Properties.Items.Add(mainForm.DC.RedLiner.TeamName);

                cmbLine.Properties.Items.Clear();
                cmbLine.Properties.Items.Add("TOP");
                cmbLine.Properties.Items.Add("JGL");
                cmbLine.Properties.Items.Add("MID");
                cmbLine.Properties.Items.Add("BOT");
                cmbLine.Properties.Items.Add("SPT");

                cmbPOGPlayer.Properties.Items.Clear();
                cmbPOGPlayer.Properties.Items.Add(mainForm.DC.BlueLiner.Top.Name);
                cmbPOGPlayer.Properties.Items.Add(mainForm.DC.BlueLiner.Jungle.Name);
                cmbPOGPlayer.Properties.Items.Add(mainForm.DC.BlueLiner.Mid.Name);
                cmbPOGPlayer.Properties.Items.Add(mainForm.DC.BlueLiner.ADCarry.Name);
                cmbPOGPlayer.Properties.Items.Add(mainForm.DC.BlueLiner.Supporter.Name);
                cmbPOGPlayer.Properties.Items.Add(mainForm.DC.RedLiner.Top.Name);
                cmbPOGPlayer.Properties.Items.Add(mainForm.DC.RedLiner.Jungle.Name);
                cmbPOGPlayer.Properties.Items.Add(mainForm.DC.RedLiner.Mid.Name);
                cmbPOGPlayer.Properties.Items.Add(mainForm.DC.RedLiner.ADCarry.Name);
                cmbPOGPlayer.Properties.Items.Add(mainForm.DC.RedLiner.Supporter.Name);

                cmbTeam.Text = strs[0];
                cmbLine.Text = strs[1];
                cmbPOGPlayer.Text = strs[2];

                if (isPOGBlue) comboBoxEdit2.SelectedIndex = 0;
                else comboBoxEdit2.SelectedIndex = 1;


                if (chk버그대비.Checked)
                {
                    DataTable dtDamage = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.현재데미지량선수).Tables[0];
                    DataTable dtGameEnd = new DataTable();
                    try
                    {
                        dtGameEnd = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.경기종료정보).Tables[DBDefine.요청데이터분류.경기종료정보.GetStringValue()];
                    }
                    catch (Exception ex) { }

                    int gameTime = Convert.ToInt32(dtGameEnd.Rows[0][1].ToString());
                    double 개인데미지 = 0;
                    double 팀데미지총합 = 0;
                    foreach (DataRow r in dtDamage.Rows)
                    {
                        if (r["챔피언이름"].Equals(lblChampEng.Text)) 개인데미지 = Convert.ToDouble(r["총가한데미지"]);

                        if (isPOGBlue && r["팀"].ToString().Equals("블루")) 팀데미지총합 += Convert.ToDouble(r["총가한데미지"]);
                        if (!isPOGBlue && r["팀"].ToString().Equals("레드")) 팀데미지총합 += Convert.ToDouble(r["총가한데미지"]);
                    }
                    txt3.Text = (개인데미지 / gameTime * 60).ToString("##0");
                    txt6.Text = (개인데미지 / 팀데미지총합 * 100).ToString("##0.0") + "%";
                }
            }
            catch (Exception ex)
            {
                mainForm.Log(MethodBase.GetCurrentMethod().Name + " : " + ex.Message, LogWriter.LogType.Error);
            }
            

        }

        private void btnPOG_Click(object sender, EventArgs e)
        {
            try
            {
             
                if (sender == btnPOGPreview || (sender == btnPOG && mainForm.MainLayerButton((SimpleButton)sender)))
                {

                    //int cnt = 0;
                    //string[] item = new string[] { "", "", "", "", "","" };
                    //string[] data = new string[] { "", "", "", "", "","" };

                    //if (c1.Checked)
                    //{
                    //    item[cnt] = d1.Text;
                    //    data[cnt] = txt1.Text;
                    //    cnt += 1;
                    //}
                    //if (c9.Checked)
                    //{
                    //    item[cnt] = d9.Text;
                    //    data[cnt] = txt9.Text;
                    //    cnt += 1;
                    //}                  
                    //if (c2.Checked)
                    //{
                    //    item[cnt] = d2.Text;
                    //    data[cnt] = txt2.Text;
                    //    cnt += 1;
                    //}
                    //if (c3.Checked)
                    //{
                    //    item[cnt] = d3.Text;
                    //    data[cnt] = txt3.Text;
                    //    cnt += 1;
                    //}
                    //if (c4.Checked)
                    //{
                    //    item[cnt] = d4.Text;
                    //    data[cnt] = txt4.Text;
                    //    cnt += 1;
                    //}
                    //if (cnt < 6)
                    //{
                    //    if (c5.Checked)
                    //    {
                    //        item[cnt] = d5.Text;
                    //        data[cnt] = txt5.Text;
                    //        cnt += 1;
                    //    }
                    //}
                    //if (cnt < 6)
                    //{
                    //    if (c6.Checked)
                    //    {
                    //        item[cnt] = d6.Text;
                    //        data[cnt] = txt6.Text;
                    //        cnt += 1;
                    //    }
                    //}
                    //if (cnt < 6)
                    //{
                    //    if (c7.Checked)
                    //    {
                    //        item[cnt] = d7.Text;
                    //        data[cnt] = txt7.Text;
                    //        cnt += 1;
                    //    }
                    //}
                    //if (cnt < 6)
                    //{
                    //    if (c8.Checked)
                    //    {
                    //        item[cnt] = d8.Text;
                    //        data[cnt] = txt8.Text;
                    //    }
                    //}

                    if (sender == btnPOGPreview)
                    {
                        string logoPath = Environment.CurrentDirectory + @"\Resource\Team Logo POG\" + cmbTeam.Text + "_" + comboBoxEdit1.Text + ".png";
                        try
                        {

                            if (File.Exists(logoPath))
                            {
                                pictureBox1.Image = Image.FromFile(logoPath);
                            }
                            else
                            {
                                pictureBox1.Image = null;
                                mainForm.Log($"logo file not found at: {logoPath}", LogWriter.LogType.Error);
                            }
                        }
                        catch (Exception ex)
                        {
                            mainForm.Log($"Error loading logo: {ex.Message}", LogWriter.LogType.Error);
                        }
                    }
                    else
                    {
                        mainForm.previewPath = Environment.CurrentDirectory + @"\PreView\" + DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".png";

                        var points = txtPont.Text;
                        var games = Enumerable.Range(1, 5).Select(BuildGameRow).ToList();


                        mainForm.TM.DisplayPOG(games, points, cmbTeam.Text, cmbLine.Text, lblChampEng.Text, cmbPOGPlayer.Text, isPOGBlue, sender == btnPOGPreview, mainForm.previewPath, comboBoxEdit1.Text, mainForm.comboGame.SelectedItem.ToString());
                    } 
                }
            }
            catch (Exception ex)
            {
                mainForm.Log(MethodBase.GetCurrentMethod().Name + " : " + ex.Message, LogWriter.LogType.Error);
            } 
        }

        private string[] BuildGameRow(int i)
        {
            // groupControl21 안에 txtResultGame1~5, txtChampGame1~5, txtKDAGame1~5, txtFreeTextGame1~5 가 있다고 가정
            var chk = Controls.Find($"checkEdit{i}", true).FirstOrDefault() as DevExpress.XtraEditors.CheckEdit;

            var txtResult = groupControl21.Controls[$"txtResultGame{i}"] as DevExpress.XtraEditors.TextEdit;
            var txtChamp = groupControl21.Controls[$"txtChampGame{i}"] as DevExpress.XtraEditors.TextEdit;
            var txtKda = groupControl21.Controls[$"txtKDAGame{i}"] as DevExpress.XtraEditors.TextEdit;
            var txtFree = groupControl21.Controls[$"txtFreeTextGame{i}"] as DevExpress.XtraEditors.TextEdit;

            return new[]
            {
        (chk?.Checked ?? false).ToString(),
        txtResult?.Text ?? "",
        txtChamp?.Text ?? "",
        txtKda?.Text ?? "",
        txtFree?.Text ?? ""
    };
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            mainForm.ConnectGameKey();
        }

        private void chkManualResult_CheckedChanged(object sender, EventArgs e)
        {
            groupControl2.Visible = chkManualResult.Checked;
        }

        private void chkT1Home_CheckedChanged(object sender, EventArgs e)
        {
            groupControl3.Visible = chkT1Home.Checked;
            mainForm.isT1Home = chkT1Home.Checked;
        }

        private void btnBlueColorChange_Click(object sender, EventArgs e)
        {
            LabelControl target = sender == btnBlueColorChange ? lblBlueColor : lblRedColor;
            string str = sender == btnBlueColorChange ? "Blue" : "Red";

            ColorPickEdit colorPickEdit1 = new ColorPickEdit();
            FrmColorPicker frm = new FrmColorPicker(colorPickEdit1.Properties);
            frm.StartPosition = FormStartPosition.CenterScreen;
            frm.SelectedColor = target.BackColor;
            frm.TopMost = true;
            if (frm.ShowDialog(colorPickEdit1.FindForm()) == System.Windows.Forms.DialogResult.OK)
            {
                target.BackColor = frm.SelectedColor;
                mainForm.colorSave(str, target.BackColor);
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            LabelControl target = sender == simpleButton2 ? lblWinColor : lblLossColor;
            string str = sender == simpleButton2 ? "Win" : "Loss";

            ColorPickEdit colorPickEdit1 = new ColorPickEdit();
            FrmColorPicker frm = new FrmColorPicker(colorPickEdit1.Properties);
            frm.StartPosition = FormStartPosition.CenterScreen;
            frm.SelectedColor = target.BackColor;
            frm.TopMost = true;
            if (frm.ShowDialog(colorPickEdit1.FindForm()) == System.Windows.Forms.DialogResult.OK)
            {
                target.BackColor = frm.SelectedColor;
                mainForm.colorSave(str, target.BackColor);
            }
        }

        private void comboBoxEdit2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxEdit2.SelectedIndex == 0) isPOGBlue = true;
            else isPOGBlue = false;
        }

        private void chkKDA수동_CheckedChanged(object sender, EventArgs e)
        {
            bool isVisible = chkKDA수동.Checked;

            panelControl1.Visible = isVisible;
            panelControl2.Visible = isVisible;
            label11.Visible = isVisible;
            label20.Visible = isVisible;
            txtKDABlue.Visible = isVisible;
            txtKDARed.Visible = isVisible;
        }

        
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            string[] strs = new string[] { "아이디", "챔피언", "KDA" };

            //cmbPlayer 에 현재 정보들로 집어넣는다
            DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.팟지).Tables[0];

            cmbPlayer.Properties.Items.Clear();

            foreach (DataRow dr in dt.Rows)
            {
                string name = dr[2].ToString();
                
                if (!cmbPlayer.Properties.Items.Contains(name)) cmbPlayer.Properties.Items.Add(name);
            }

            //cmbPlayer.SelectedIndex = -1;
            cmbPlayer_SelectedIndexChanged(null, null);
        }


        List<string[]> Game1 = new List<string[]>();
        List<string[]> Game2 = new List<string[]>();
        List<string[]> Game3 = new List<string[]>();
        List<string[]> Game4 = new List<string[]>();
        List<string[]> Game5 = new List<string[]>();

        private void btnGameSave_Click(object sender, EventArgs e)
        {
            try
            {
                string gameNum = cmbGame.Text;

                List<string[]> 현재게임정보 = new List<string[]>();
                DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.팟지).Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    string name = dr[2].ToString();
                    string champ = dr[3].ToString();
                    if (dr[4].ToString() == "") dr[4] = "0";
                    if (dr[5].ToString() == "") dr[5] = "0";
                    if (dr[6].ToString() == "") dr[6] = "0";
                    string KDA = dr[4] + "/" + dr[5] + "/" + dr[6];
                    string team = dr[1].ToString();

                    string[] strs = new string[] { name, champ, KDA, team };
                    현재게임정보.Add(strs);
                }

                //게임 결과 저장용
                try
                {
                    DataTable dtGameEnd = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.경기종료정보).Tables[DBDefine.요청데이터분류.경기종료정보.GetStringValue()];
                    string 이긴팀 = dtGameEnd.Rows[0][0].ToString();

                    string[] strs2 = new string[] { "이긴팀", 이긴팀, "", "" };
                    현재게임정보.Add(strs2);
                }
                catch (Exception ex)
                {

                }


                if (gameNum.Contains("1")) Game1 = 현재게임정보;
                if (gameNum.Contains("2")) Game2 = 현재게임정보;
                if (gameNum.Contains("3")) Game3 = 현재게임정보;
                if (gameNum.Contains("4")) Game4 = 현재게임정보;
                if (gameNum.Contains("5")) Game5 = 현재게임정보;

                colorCheck();

                MessageBox.Show("정보를 저장하였습니다. 5게임 제외, 다음 게임 인덱스로 변경됩니다.");

                cmbGame.SelectedIndex = cmbGame.SelectedIndex + 1;

                cmbPlayer_SelectedIndexChanged(null, null);
            }
            catch(Exception ex)
            {

            }
          
        }

        private void colorCheck()
        {
            var disabled = Color.FromArgb(200, 200, 200);
            var enabled = Color.FromArgb(40, 40, 40);

            lblGame1.ForeColor = (Game1.Count == 0) ? disabled : enabled;
            lblGame2.ForeColor = (Game2.Count == 0) ? disabled : enabled;
            lblGame3.ForeColor = (Game3.Count == 0) ? disabled : enabled;
            lblGame4.ForeColor = (Game4.Count == 0) ? disabled : enabled;
            lblGame5.ForeColor = (Game5.Count == 0) ? disabled : enabled;

            checkEdit1.Checked = (Game1.Count != 0);
            checkEdit2.Checked = (Game2.Count != 0);
            checkEdit3.Checked = (Game3.Count != 0);
            checkEdit4.Checked = (Game4.Count != 0);
            checkEdit5.Checked = (Game5.Count != 0);
        }

        private void cmbPlayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            string name = cmbPlayer.Text;
            string team = "";
            string champName = ""; 
            DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.팟지).Tables[0]; 
            foreach (DataRow dr in dt.Rows)
            {
                if (dr[2].ToString().Equals(name))
                {
                    team = dr[1].ToString();
                    champName = dr[3].ToString();
                }  
            }
            
            foreach (var v in DataManager.getInstance().mChampionTable)
            {
                if (v.Value.champNameENG.Equals(champName))
                {
                    int index = cmbPOG.Properties.Items.IndexOf(v.Value.champNameKOR);
                    cmbPOG.SelectedIndex = index;
                    break;
                }
            }

            //확인 끝

            for (int i = 1; i < 6; i++)
            {
                groupControl21.Controls["txtResultGame" + i].Text = "GAME  "+ i + " - ";
                groupControl21.Controls["txtChampGame" + i].Text = "";
                groupControl21.Controls["txtKDAGame" + i].Text = "";

                List<string[]> target = new List<string[]>();

                if (i == 1) target = Game1;
                if (i == 2) target = Game2;
                if (i == 3) target = Game3;
                if (i == 4) target = Game4;
                if (i == 5) target = Game5;

                string 승리팀 = "";
                foreach( var v in target)
                {
                    if (v[0].Equals("이긴팀")) 승리팀 = v[1];
                }

                foreach (var v in target)
                {
                    //string[] strs = new string[] { "아이디", "챔피언", "KDA", "팀" };
                    if (v[0].Equals(name))
                    {
                        groupControl21.Controls["txtChampGame" + i].Text = v[1];
                        groupControl21.Controls["txtKDAGame" + i].Text = v[2];

                        try
                        {
                            string WL = v[3].Equals(승리팀) ? "W" : "L";
                            groupControl21.Controls["txtResultGame" + i].Text = "GAME  " + i + " - " + WL;
                        }
                        catch(Exception ex) { }
                        
                    }
                }
            }
        }

        private void btnAllSave_Click(object sender, EventArgs e)
        {
            try
            {
                var ds = new DataSet("SavedGames");

                ds.Tables.Add(ToGameTable("Game1", Game1));
                ds.Tables.Add(ToGameTable("Game2", Game2));
                ds.Tables.Add(ToGameTable("Game3", Game3));
                ds.Tables.Add(ToGameTable("Game4", Game4));
                ds.Tables.Add(ToGameTable("Game5", Game5));

                string path = GetSaveFilePath();

                // 스키마 포함 저장(컬럼 구조 유지)
                ds.WriteXml(path, XmlWriteMode.WriteSchema);

                MessageBox.Show("저장 완료: " + path);
            }
            catch (Exception ex)
            {
                MessageBox.Show("저장 실패: " + ex.Message);
            }
        }


        private void btnAllLoad_Click(object sender, EventArgs e)
        {
            try
            {
                string path = GetSaveFilePath();

                if (!File.Exists(path))
                {
                    MessageBox.Show("저장 파일이 없습니다: " + path);
                    return;
                }

                var ds = new DataSet();
                ds.ReadXml(path);

                Game1 = FromGameTable(ds.Tables["Game1"]);
                Game2 = FromGameTable(ds.Tables["Game2"]);
                Game3 = FromGameTable(ds.Tables["Game3"]);
                Game4 = FromGameTable(ds.Tables["Game4"]);
                Game5 = FromGameTable(ds.Tables["Game5"]);

                colorCheck();

                MessageBox.Show("로드 완료: " + path);
            }
            catch (Exception ex)
            {
                MessageBox.Show("로드 실패: " + ex.Message);
            }
        }


        private string GetSaveFilePath()
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SavedGames.xml");
        }

        private DataTable ToGameTable(string tableName, List<string[]> game)
        {
            var t = new DataTable(tableName);
            t.Columns.Add("아이디");
            t.Columns.Add("챔피언");
            t.Columns.Add("KDA");
            t.Columns.Add("팀");   // 추가

            if (game == null) return t;

            foreach (var arr in game)
            {
                var r = t.NewRow();
                r["아이디"] = (arr != null && arr.Length > 0) ? arr[0] : "";
                r["챔피언"] = (arr != null && arr.Length > 1) ? arr[1] : "";
                r["KDA"] = (arr != null && arr.Length > 2) ? arr[2] : "";
                r["팀"] = (arr != null && arr.Length > 3) ? arr[3] : "";  // 추가
                t.Rows.Add(r);
            }

            return t;
        }

        private List<string[]> FromGameTable(DataTable t)
        {
            var list = new List<string[]>();
            if (t == null) return list;

            bool hasTeamCol = t.Columns.Contains("팀");

            foreach (DataRow dr in t.Rows)
            {
                string id = dr["아이디"]?.ToString() ?? "";
                string champ = dr["챔피언"]?.ToString() ?? "";
                string kda = dr["KDA"]?.ToString() ?? "";
                string team = hasTeamCol ? (dr["팀"]?.ToString() ?? "") : "";

                list.Add(new string[] { id, champ, kda, team });
            }

            return list;
        }

        private void btnPOMInit_Click(object sender, EventArgs e)
        {
            cmbGame.SelectedIndex = 0;

            Game1 = new List<string[]>();
            Game2 = new List<string[]>();
            Game3 = new List<string[]>();
            Game4 = new List<string[]>();
            Game5 = new List<string[]>();

            colorCheck();

            MessageBox.Show("정보 초기화.. Game1부터 새로 저장 후 진행해야 합니다.");
        }
    }
}
