using DevExpress.Utils;
using DevExpress.XtraCharts;
using DevExpress.XtraEditors;
using lol_coder.Data;
using lol_coder.Form;
using lol_coder.Forms;
using lol_coder.Forms.Frame;
using lol_coder.Log;
using lol_coder.Tornado;
using LolDataRequestLib;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static lol_coder.Data.DataControl;
using static lol_coder.Log.LogWriter;

namespace lol_coder
{
    public partial class MainForm : XtraForm, IGameTimeEventDrop
    {
        public DataControl DC = new DataControl();

        public BanPickFrame banPickFrame;
        public RunePageFrame runePageFrame;
        public LiveCoderFrame liveCoderFrame;
        public ResultFrame resultFrame;
        public DataFrame dataFrame;


        #region 생성자

        public MainForm()
        {
            InitializeComponent();

            
            TM = TornadoManager.getInstance();
            TM.setMainFrom(this);

            LW = LogWriter.getInstance();
            LW.LogFileName = String.Format("{0}", DateTime.Now.ToString("yyMMdd hhmmss"));

            DC = DataControl.getInstance();
            DC.LoadTeams();

            RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey);
            if (key.GetValue("version") != null) textpatch.Text = key.GetValue("version").ToString();  
            if (key.GetValue("IP") != null) txtip.Text = key.GetValue("IP").ToString();
            if (key.GetValue("OutFrame") != null) txtOutFrame.Text = key.GetValue("OutFrame").ToString();

            if (key.GetValue("game") != null) txtgame.Text = key.GetValue("game").ToString();
            if (key.GetValue("code") != null) txtCode.Text = key.GetValue("code").ToString();

            if (key.GetValue("Match") != null) MatchText.Text = key.GetValue("Match").ToString();
            if (key.GetValue("textEdit3") != null) textEdit3.Text = key.GetValue("textEdit3").ToString();
            //Match, textEdit3

            key.Close();


            banPickFrame = new BanPickFrame(this);
            navigationPage1.Controls.Add(banPickFrame);

            runePageFrame = new RunePageFrame(this);
            navigationPage2.Controls.Add(runePageFrame);

            liveCoderFrame = new LiveCoderFrame(this);
            navigationPage3.Controls.Add(liveCoderFrame);

            resultFrame = new ResultFrame(this);
            navigationPage4.Controls.Add(resultFrame);

            dataFrame = new DataFrame(this);
            navigationPage5.Controls.Add(dataFrame);

            key = Registry.CurrentUser.CreateSubKey(subKey);
            if (key.GetValue("Blue") != null) resultFrame.lblBlueColor.BackColor = Color.FromArgb((int)key.GetValue("Blue"));
            if (key.GetValue("Red") != null) resultFrame.lblRedColor.BackColor = Color.FromArgb((int)key.GetValue("Red"));

            if (key.GetValue("Win") != null) resultFrame.lblWinColor.BackColor = Color.FromArgb((int)key.GetValue("Win"));
            if (key.GetValue("Loss") != null) resultFrame.lblLossColor.BackColor = Color.FromArgb((int)key.GetValue("Loss"));

            key.Close();
            
        }

        #endregion


        #region MainForm Events

        bool isFormClosing = false;

        private void MainForm_Shown(object sender, EventArgs e)
        {
            LoadSettingCoder();

            CheckStartTornado();

            accordion_Click(accordionBanPick, new EventArgs());

            //임시
            //폼 로드 시 우선 T1 vs GEN 로 기본 셋팅한다
            //선택한 팀의 맴버를 저장
            string blue = "T1A";
            DC.LoadPlayer(blue);
            var blueTeam = DC.Teams.Find(x => x.TeamName.Equals(blue));

            DC.BlueLiner.TeamName = blue;
            DC.BlueLiner.Top.Name = blueTeam.Players.Find(x => x.Item2.Equals("탑") && x.Item3.Equals(true)).Item1;
            DC.BlueLiner.Jungle.Name = blueTeam.Players.Find(x => x.Item2.Equals("정글") && x.Item3.Equals(true)).Item1;
            DC.BlueLiner.Mid.Name = blueTeam.Players.Find(x => x.Item2.Equals("미드") && x.Item3.Equals(true)).Item1;
            DC.BlueLiner.ADCarry.Name = blueTeam.Players.Find(x => x.Item2.Equals("원딜") && x.Item3.Equals(true)).Item1;
            DC.BlueLiner.Supporter.Name = blueTeam.Players.Find(x => x.Item2.Equals("서폿") && x.Item3.Equals(true)).Item1;

            string red = "GGA";
            DC.LoadPlayer(red);
            var redTeam = DC.Teams.Find(x => x.TeamName.Equals(red));

            DC.RedLiner.TeamName = red;
            DC.RedLiner.Top.Name = redTeam.Players.Find(x => x.Item2.Equals("탑") && x.Item3.Equals(true)).Item1;
            DC.RedLiner.Jungle.Name = redTeam.Players.Find(x => x.Item2.Equals("정글") && x.Item3.Equals(true)).Item1;
            DC.RedLiner.Mid.Name = redTeam.Players.Find(x => x.Item2.Equals("미드") && x.Item3.Equals(true)).Item1;
            DC.RedLiner.ADCarry.Name = redTeam.Players.Find(x => x.Item2.Equals("원딜") && x.Item3.Equals(true)).Item1;
            DC.RedLiner.Supporter.Name = redTeam.Players.Find(x => x.Item2.Equals("서폿") && x.Item3.Equals(true)).Item1;

            selectTeamText();

            //커넥션 우선 시도
            TM.Connection();

            liveCoderFrame.radioGroup3.SelectedIndex = 1;
        }   

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("WDG League of Legends Coder를 종료하시겠습니까?", "종료", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                isFormClosing = true;
                TornadoAliveCheckThread.Abort();
                Dispose(true);
                Application.Exit();
            }
            else
            {
                e.Cancel = true;
            }
        }

        #endregion


        #region Accordion Events

        

        private void accordion_Click(object sender, EventArgs e)
        {
            try
            {
                if (sender == accordionBanPick) navigationFrame1.SelectedPage = navigationPage1;
                else if (sender == accordionRuneKeystone) navigationFrame1.SelectedPage = navigationPage2;
                else if (sender == accordionLiveCoder) navigationFrame1.SelectedPage = navigationPage3;
                else if (sender == accordionResult)
                {
                    navigationFrame1.SelectedPage = navigationPage4;
                    //POG
                    resultFrame.cmbRefresh();
                }
                else if (sender == accordionControlElement1) navigationFrame1.SelectedPage = navigationPage5;

                //백픽 데이터는 해당 Frame이 활성화 되어 있을때만 시작한다
                banPickFrame.TimerSwitch(sender == accordionBanPick);

                //룬페이지 정보를 챔피언에 담는다.
                if (sender == accordionLiveCoder || sender == accordionResult)
                {
                    DataTable dt = getRunData();

                    if (dt.Rows.Count > 9)
                    {
                        for (int i = 0; i < 10; i++)
                        {
                            Liners liners = i < 5 ? DC.BlueLiner : DC.RedLiner;

                            Liner liner = i < 5 ? liners.GetLiner(i) : liners.GetLiner(i - 5);
                            liner.champ = dt.Rows[i][2].ToString();
                            liners.SetLiner(i < 5 ? i : i - 5, liner);
                        }
                    }
                }

                AccordionTextColor(sender);
            }
            catch(Exception ex)
            {

            }
            
        }


        private void AccordionTextColor(object sender)
        {
            foreach (var c in accordionControl1.Elements)
            {
                if (c != sender)
                {
                    c.Appearance.Normal.ForeColor = Color.Black;

                    foreach (var c2 in c.Elements)
                    {
                        if (c2 != sender) c2.Appearance.Normal.ForeColor = Color.Black;
                        else c2.Appearance.Normal.ForeColor = Color.Red;
                    }

                }
                else c.Appearance.Normal.ForeColor = Color.Red;
            }
        }

        #endregion
         

        #region 설정값 저장 및 로드 - Coder

        private readonly string OptionCoderPath = Environment.CurrentDirectory + @"\Data\optionCoder.json";

        private void LoadSettingCoder()
        {
            /*
            try
            {
                if (File.Exists(OptionCoderPath))
                {
                    using (StreamReader file = new StreamReader(OptionCoderPath))
                    {
                        using (JsonTextReader reader = new JsonTextReader(file))
                        {
                            JObject json = (JObject)JToken.ReadFrom(reader);

                            TM.IP = json["TornadoIP"].ToString();
                            TM.Port = Convert.ToInt32(json["TornadoPort"]);
                            TM.DissolveTime = Convert.ToInt32(json["DissolveTime"]); 
                          
                            CheckTimeTornado = Convert.ToInt32(json["CheckTimeTornado"]); 

                            LW.isShowLogNormal = Convert.ToBoolean(json["isShowLogNormal"]);
                            LW.isShowLogDisplay = Convert.ToBoolean(json["isShowLogDisplay"]);
                            LW.isShowLogError = Convert.ToBoolean(json["isShowLogError"]);

                            LW.colorLogNormal = Color.FromArgb(Convert.ToInt32(json["colorLogNormal"]));
                            LW.colorLogDisplay = Color.FromArgb(Convert.ToInt32(json["colorLogDisplay"]));
                            LW.colorLogError = Color.FromArgb(Convert.ToInt32(json["colorLogError"]));

                            LW.isSaveLogNormal = Convert.ToBoolean(json["isSaveLogNormal"]);
                            LW.isSaveLogDisplay = Convert.ToBoolean(json["isSaveLogDisplay"]);
                            LW.isSaveLogError = Convert.ToBoolean(json["isSaveLogError"]);

                            txtTornadoIP.Text = TM.IP;
                            txtTornadoPort.Text = TM.Port.ToString();
                            //임시 - DissolveTime 처리 관련 결정해야함

                            txtAPIURL.Text = API.BaseURL;
                            txtTornadoCheckTime.Text = (CheckTimeTornado / 1000).ToString();
                            txtAPICheckTime.Text = (CheckTimeAPI / 1000).ToString();

                            toggleShowLogNormal.IsOn = LW.isShowLogNormal;
                            toggleShowLogDisplay.IsOn = LW.isShowLogDisplay;
                            toggleShowLogError.IsOn = LW.isShowLogError;

                            colorPickLogNormal.Color = LW.colorLogNormal;
                            colorPickLogDisplay.Color = LW.colorLogDisplay;
                            colorPickLogError.Color = LW.colorLogError;

                            toggleSaveLogNormal.IsOn = LW.isSaveLogNormal;
                            toggleSaveLogDisplay.IsOn = LW.isSaveLogDisplay;
                            toggleSaveLogError.IsOn = LW.isSaveLogError;
                        }
                    }
                }

                ColorCheck();
            }
            catch (Exception ex)
            {
                Log(MethodBase.GetCurrentMethod().Name + " : " + ex.Message, LogWriter.LogType.Error);
            }
            */
        }

        private void SaveSettingCoder()
        {
            /*
            try
            {
                JObject json = new JObject();
                json.Add("TornadoIP", TM.IP);
                json.Add("TornadoPort", TM.Port);
                json.Add("DissolveTime", TM.DissolveTime);
                 

                json.Add("CheckTimeTornado", CheckTimeTornado); 

                json.Add("isShowLogNormal", LW.isShowLogNormal);
                json.Add("isShowLogDisplay", LW.isShowLogDisplay);
                json.Add("isShowLogError", LW.isShowLogError);

                json.Add("colorLogNormal", LW.colorLogNormal.ToArgb());
                json.Add("colorLogDisplay", LW.colorLogDisplay.ToArgb());
                json.Add("colorLogError", LW.colorLogError.ToArgb());

                json.Add("isSaveLogNormal", LW.isSaveLogNormal);
                json.Add("isSaveLogDisplay", LW.isSaveLogDisplay);
                json.Add("isSaveLogError", LW.isSaveLogError);

                File.WriteAllText(OptionCoderPath, json.ToString());

                Log("코더 셋팅 값 저장 성공", LogWriter.LogType.Normal);
            }
            catch (Exception ex)
            {
                Log(MethodBase.GetCurrentMethod().Name + " : " + ex.Message, LogWriter.LogType.Error);
            }

            ColorCheck();
            */
        }

        #endregion


        #region Torando

        public TornadoManager TM;
        private System.Threading.Thread TornadoAliveCheckThread = null;
        private int CheckTimeTornado = 3000;
        private LabelControl AliveControlTornado;
        private bool isReqeustHeartbeat = false;
        private Color AliveColor = Color.FromArgb(0, 192, 0);
        private Color DeadColor = Color.FromArgb(192, 0, 0);

        public string previewPath = "";
        internal void OnLogMessage(string logMessage)
        {
            if (!logMessage.Contains("[SUCCESS]")) Log("Tornado2" + logMessage, LogType.Display);

           
            if (logMessage.Contains("[SUCCESS]  DOWNLOAD_THUMBNAIL"))
            {
                try
                {
                    if (File.Exists(previewPath))
                    {
                        System.Threading.Thread.Sleep(200);
                        resultFrame.pictureBox1.Image = Image.FromFile(previewPath);
                    }
                    else
                    {
                        Log($"Thumbnail file not found at: {previewPath}", LogType.Error);
                    }
                }
                catch (Exception ex)
                {
                    Log($"Error loading thumbnail: {ex.Message}", LogType.Error);
                }
            }
        }

        internal void OnHeartBeat(int bSuccess)
        {
            isReqeustHeartbeat = false;
        }



        //Alive Check
        private void CheckStartTornado()
        {
            TornadoAliveCheckThread = new System.Threading.Thread(new System.Threading.ThreadStart(CheckWorkerTornado));
            TornadoAliveCheckThread.Start();
            AliveControlTornado = lblConnectionTornado2;
        }

        private void CheckWorkerTornado()
        {
            while (true)
            {
                try
                {
                    isReqeustHeartbeat = true;
                    TM.AliveCheck();
                    System.Threading.Thread.Sleep(CheckTimeTornado);


                    Color color = !isReqeustHeartbeat ? AliveColor : DeadColor;
                     

                    if (this.InvokeRequired)
                    {                        
                        this.Invoke((MethodInvoker)(() => AliveControlTornado.BackColor = color));
                         
                    }
                    else
                    {
                        AliveControlTornado.BackColor = color;
                        
                    }

                    if (isReqeustHeartbeat) TM.Connection();
                }
                catch (Exception ex)
                {
                    Log(MethodBase.GetCurrentMethod().Name + " : " + ex.Message, LogWriter.LogType.Error);
                }

            }
        }



        //Tornado2 실행
        private void picTornado_MouseClick(object sender, MouseEventArgs e)
        {
            System.Diagnostics.Process.Start(@"C:\Tornado2\Tornado2.exe");
        }

        #endregion


        #region Log, Resource Check

        LogWriter LW;

        public void Log(string logMessage, LogType logType)
        {
            try {
                Color txtcolor;

                if (logType == LogType.Normal) txtcolor = LW.colorLogNormal;
                else if (logType == LogType.Display) txtcolor = LW.colorLogDisplay;
                else txtcolor = LW.colorLogError; //LogType.Error




                if ((logType == LogType.Normal && LW.isShowLogNormal) ||
                (logType == LogType.Display && LW.isShowLogDisplay) ||
                (logType == LogType.Error && LW.isShowLogError))
                {
                    if (isFormClosing) return;

                    Invoke((Action)(() =>
                    {

                        txtLog.SelectionStart = this.txtLog.TextLength;
                        txtLog.SelectionColor = Color.Green;
                        txtLog.SelectionStart = this.txtLog.TextLength;
                        txtLog.SelectionColor = txtcolor;
                        //txtLog.AppendText(Environment.NewLine + DateTime.Now.ToString("[HH:mm:ss.fff] ") + logMessage);
                        txtLog.AppendText(Environment.NewLine +  logMessage);
                        txtLog.SelectionStart = this.txtLog.TextLength;
                        txtLog.SelectionColor = SystemColors.WindowText;

                        txtLog.SelectionStart = txtLog.Text.Length;
                        txtLog.ScrollToCaret();

                    }
                    ));
                }

                if ((logType == LogType.Normal && LW.isSaveLogNormal) ||
                    (logType == LogType.Display && LW.isSaveLogDisplay) ||
                    (logType == LogType.Error && LW.isSaveLogError))
                {
                    LW.LogWrite(logMessage, logType);
                }
            }
            catch (Exception ex) { }
            
        }

        private void btnResourceCheck_Click(object sender, EventArgs e)
        {
            Log("이미지 리소스 체크를 시작합니다.", LogType.Normal);

            //룬 이미지 체크
            foreach (var v in DataManager.getInstance().mRuneTable)
            {
                string path = Environment.CurrentDirectory + @"\Resource\Runes(140x140)\" + v.Value + ".png";
                path = path.Replace("Legend:", "Legend");
                if (!File.Exists(path)) Log("룬 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);

                path = Environment.CurrentDirectory + @"\Resource\Runes(512x512)\" + v.Value + ".png";
                path = path.Replace("Legend:", "Legend");
                if (!File.Exists(path)) Log("룬 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);
            }

            //챔피언 이미지 체크
            foreach (var v in DataManager.getInstance().mChampionTable)
            {
                Log(v.Value.champNameENG.ToUpper(), LogType.Error);
                string path = Environment.CurrentDirectory + @"\Resource\Champs(140x140)\" + v.Value.champNameENG + "_140140.png";
                if (!File.Exists(path)) Log("챔피언 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);

                path = Environment.CurrentDirectory + @"\Resource\Champs(520x370)\" + v.Value.champNameENG + "_L.png";
                if (!File.Exists(path)) Log("챔피언 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);
                path = Environment.CurrentDirectory + @"\Resource\Champs(520x370)\" + v.Value.champNameENG + "_R.png";
                if (!File.Exists(path)) Log("챔피언 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);

                path = Environment.CurrentDirectory + @"\Resource\Champs(620x130)\" + v.Value.champNameENG + "_L.png";
                if (!File.Exists(path)) Log("챔피언 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);
                path = Environment.CurrentDirectory + @"\Resource\Champs(620x130)\" + v.Value.champNameENG + "_R.png";
                if (!File.Exists(path)) Log("챔피언 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);

                path = Environment.CurrentDirectory + @"\Resource\Champs(1215x717)\" + v.Value.champNameENG + "_L.png";
                if (!File.Exists(path)) Log("챔피언 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);
                path = Environment.CurrentDirectory + @"\Resource\Champs(1215x717)\" + v.Value.champNameENG + "_R.png";
                if (!File.Exists(path)) Log("챔피언 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error); 

                path = Environment.CurrentDirectory + @"\Resource\Champs(158x245)\" + v.Value.champNameENG + "_158245.png";
                if (!File.Exists(path)) Log("챔피언 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);
            }



            //POG 이미지 체크
            DC.LoadTeams();
            List<string> teamNames = new List<string>();
            for (int i = 0; i < DC.Teams.Count; i++)
            {
                teamNames.Add(DC.Teams[i].TeamName);                
            }
            for (int i = 0; i < teamNames.Count; i++)
            {
                DC.LoadPlayer(teamNames[i]);
            }
            foreach (var p in DC.Teams)
            {
                foreach (var v in p.Players)
                {
                    string path = Environment.CurrentDirectory + @"\T2S\TeamLogo\POG\" + p.TeamName + "\\" + v.Item1 + ".png";
                    if (!File.Exists(path)) Log("선수POG 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);

                    string path2 = Environment.CurrentDirectory + @"\T2S\TeamLogo\LineUp\" + p.TeamName + "\\" + v.Item1 + ".png";
                    if (!File.Exists(path2)) Log("선수LineUp 이미지 " + path2 + " 가 존재하지 않습니다.", LogType.Error);
                }
            }

            //팀 로고 체크
            foreach (var p in DC.Teams)
            {
                string path = Environment.CurrentDirectory + @"\Resource\TeamLogo_W\" + p.TeamName + ".png";
                if (!File.Exists(path)) Log("팀이 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);

                path = Environment.CurrentDirectory + @"\Resource\Team Logo(1080x1080)\" + p.TeamName + ".png";
                if (!File.Exists(path)) Log("팀이 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);

                path = Environment.CurrentDirectory + @"\Resource\Team Logo POG\" + p.TeamName + "_A.png";
                if (!File.Exists(path)) Log("팀이 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);

                path = Environment.CurrentDirectory + @"\Resource\Team Logo POG\" + p.TeamName + "_B.png";
                if (!File.Exists(path)) Log("팀이 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);

                path = Environment.CurrentDirectory + @"\Resource\Team Logo POG\" + p.TeamName + "_C.png";
                if (!File.Exists(path)) Log("팀이 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);

                path = Environment.CurrentDirectory + @"\Resource\Team Logo POG\" + p.TeamName + "_D.png";
                if (!File.Exists(path)) Log("팀이 이미지 " + path + " 가 존재하지 않습니다.", LogType.Error);
            }

            //아타칸 정보 리소스 체크
            /*
            string newPath = Environment.CurrentDirectory + @"\Resource\MonsterRename\ThornboundAtakhan.png";
            if (!File.Exists(newPath)) Log("아타칸 이미지 " + newPath + " 가 존재하지 않습니다.", LogType.Error);

            for (int i = 0; i < 4; i++)
            {
                newPath = Environment.CurrentDirectory + @"\Res\무력행사\EpicMonster_" + i + ".png";
                if (!File.Exists(newPath)) Log("아타칸 이미지 " + newPath + " 가 존재하지 않습니다.", LogType.Error);

                if (i < 2)
                {
                    newPath = Environment.CurrentDirectory + @"\Res\무력행사\FirstBlood_" + i + ".png";
                    if (!File.Exists(newPath)) Log("아타칸 이미지 " + newPath + " 가 존재하지 않습니다.", LogType.Error);

                    newPath = Environment.CurrentDirectory + @"\Res\무력행사\Turret_" + i + ".png";
                    if (!File.Exists(newPath)) Log("아타칸 이미지 " + newPath + " 가 존재하지 않습니다.", LogType.Error);
                }
            }
            */
             

            Log("이미지 리소스 체크를 완료했습니다.", LogType.Normal);
        }

        private void btnLogClear_Click(object sender, EventArgs e)
        {
            txtLog.Clear();
        }

        #endregion


        #region IGameTimeEventDrop

        public string GetTime(string t) { if (t.Length == 1) t = "0" + t; return t; }

        public void 현재게임시간(int 초)
        {
            try
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    mTime.Text = GetTime((초 / 60).ToString());
                    sTime.Text = GetTime((초 % 60).ToString());
                }));
            }
            catch(Exception ex) { }
            
        }

        public string NowGameTime(bool isMin) => isMin ? mTime.Text : sTime.Text;

         

        public void 드래곤리스폰시간(string 용종류, int 남은시간_단위_초)
        {
            try
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    if (!liveCoderFrame.ck3.Checked)
                    {
                        if (용종류 == "fire")
                            liveCoderFrame.ComboRow.SelectedIndex = 0;
                        else if (용종류 == "earth")
                            liveCoderFrame.ComboRow.SelectedIndex = 1;
                        else if (용종류 == "water")
                            liveCoderFrame.ComboRow.SelectedIndex = 2;
                        else if (용종류 == "air")
                            liveCoderFrame.ComboRow.SelectedIndex = 3;
                        else if (용종류 == "hextech")
                            liveCoderFrame.ComboRow.SelectedIndex = 4;
                        else if (용종류 == "chemtech")
                            liveCoderFrame.ComboRow.SelectedIndex = 5;
                        else if (용종류 == "elder")
                            liveCoderFrame.ComboRow.SelectedIndex = 6;


                        if (liveCoderFrame.chkDragonBugFix.Checked)
                        {
                        
                                                   
                        }
                        else
                        {
                            liveCoderFrame.dt1.Text = GetTime((남은시간_단위_초 / 60).ToString());
                            liveCoderFrame.dt2.Text = GetTime((남은시간_단위_초 % 60).ToString());

                            if (liveCoderFrame.dt1.Text == "00" && liveCoderFrame.dt2.Text == "00")
                            {
                                liveCoderFrame.dt2.Text = "LIVE";
                            }
                        }
                        
                    }
                }));
            }
            catch (Exception ex)
            {

            }
   
        }

        public void 오브젝트리스폰시간(string 오브젝트잡은팀, string 오브젝트종류, int 게임시간_단위_초)
        {
            try
            {
                this.Invoke(new MethodInvoker(() =>
                { 
                    if (오브젝트종류 == "baron")
                    {
                        if (!liveCoderFrame.ck4.Checked)
                        {
                            liveCoderFrame.bt1.Text = GetTime((게임시간_단위_초 / 60).ToString());
                            liveCoderFrame.bt2.Text = GetTime((게임시간_단위_초 % 60).ToString());

                            if (liveCoderFrame.bt1.Text == "00" && liveCoderFrame.bt2.Text == "00")
                            {
                                liveCoderFrame.bt2.Text = "LIVE";
                            }
                        }
                    }
                    else if (오브젝트종류 == "riftHerald")
                    {
                        if (!liveCoderFrame.ck1.Checked)
                        {

                            liveCoderFrame.ht1.Text = GetTime((게임시간_단위_초 / 60).ToString());
                            liveCoderFrame.ht2.Text = GetTime((게임시간_단위_초 % 60).ToString());

                            if (liveCoderFrame.ht1.Text == "00" && liveCoderFrame.ht2.Text == "00")
                            {
                                liveCoderFrame.ht2.Text = "LIVE";
                            }
                        }
                    }
                    else if (오브젝트종류 == "atakhan")
                    {
                        if (!liveCoderFrame.ck10.Checked)
                        {

                            liveCoderFrame.at1.Text = GetTime((게임시간_단위_초 / 60).ToString());
                            liveCoderFrame.at2.Text = GetTime((게임시간_단위_초 % 60).ToString());

                            if (liveCoderFrame.at1.Text == "00" && liveCoderFrame.at2.Text == "00")
                            {
                                liveCoderFrame.at2.Text = "LIVE";
                            }
                        }
                    }
                    else if (오브젝트종류.Contains("Atakhan"))
                    {
                        liveCoderFrame.textEdit1.Text = "잡은팀 : " + 오브젝트잡은팀;
                        liveCoderFrame.textEdit2.Text = 오브젝트종류;
                        liveCoderFrame.textEdit3.Text = 게임시간_단위_초.ToString()+ " Sec";

                        if (오브젝트잡은팀 == "블루") { }
                        else { }
                    }
                    else if (오브젝트종류 == "horde")
                    {
                        if (!liveCoderFrame.ck9.Checked)
                        {

                            liveCoderFrame.hordet1.Text = GetTime((게임시간_단위_초 / 60).ToString());
                            liveCoderFrame.hordet2.Text = GetTime((게임시간_단위_초 % 60).ToString());

                            if (liveCoderFrame.hordet1.Text == "00" && liveCoderFrame.hordet2.Text == "00")
                            {
                                liveCoderFrame.hordet2.Text = "LIVE";
                            }
                        }
                    }

                }));
            }
            catch(Exception ex) { }
        } 

        public void 오브젝트버프시간(string 오브젝트잡은팀, string 오브젝트종류, int 게임시간_단위_초, int 파워플레이골드)
        {
            try
            {
                this.Invoke(new MethodInvoker(() =>
            {
                if (오브젝트종류 == "baron")
                {
                    if (오브젝트잡은팀 == "블루")
                    {

                        liveCoderFrame.BaronGroup.SelectedIndex = 0; 
                    }

                    else
                    {
                        liveCoderFrame.BaronGroup.SelectedIndex = 1; 
                    }


                    if (!liveCoderFrame.ck7.Checked)
                    {
                        liveCoderFrame.br1.Text = GetTime((게임시간_단위_초 / 60).ToString());
                        liveCoderFrame.br2.Text = GetTime((게임시간_단위_초 % 60).ToString());
                    }

                    string ppGold = "";

                    if (파워플레이골드 > 0)
                        ppGold = "+" + 파워플레이골드.ToString();// + " G";
                    else
                        ppGold = 파워플레이골드.ToString();// + " G";

                    liveCoderFrame.txtgold.Text = ppGold;
                    /*
                    if (TM.isDisplayBaronPowerPlay)
                    {
                        TM.DisplayBaronPowerPlay(false, ppGold, false);
                    }
                    */
                }

                else //-- 엘더 버프
                {
                    if (오브젝트잡은팀 == "블루")
                        liveCoderFrame.ElderGroup.SelectedIndex = 0;
                    else
                        liveCoderFrame.ElderGroup.SelectedIndex = 1;

                    if (!liveCoderFrame.ck8.Checked)
                    {

                        liveCoderFrame.ed1.Text = GetTime((게임시간_단위_초 / 60).ToString());
                        liveCoderFrame.ed2.Text = GetTime((게임시간_단위_초 % 60).ToString());
                    }
                }
            }));
            }
            catch (Exception ex) { }
        }

        public void 공허유충정보(int 블루팀공허유충, int 레드팀공허유충)
        {
            try
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    //디자인 표출에 따른 제공..
                    liveCoderFrame.BHorde.Text = 블루팀공허유충.ToString();
                    liveCoderFrame.RHorde.Text = 레드팀공허유충.ToString();
                }));
            }
            catch (Exception ex) { }

        }

        public void 억제기리스폰시간(DataTable 터진억제기정보)
        {
            try
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    string[] tag = new string[10];
                    string[] data = new string[10];

                    foreach (DataRow item in 터진억제기정보.Rows)
                    {
                        if (item["타워부서진팀"].ToString() == "블루")
                        {
                            if (item["넥서스타워"].ToString() == "")
                            {

                                if (item["파괴된라인"].ToString() == "top")
                                {
                                    //item["남은시간(초)"]
                                    liveCoderFrame.bbt1.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) / 60).ToString());
                                    liveCoderFrame.bbt2.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) % 60).ToString());

                                    tag[1] = "B_Timer_Top"; data[1] = liveCoderFrame.bbt1.Text.Substring(1) + ":" + liveCoderFrame.bbt2.Text;

                                }
                                if (item["파괴된라인"].ToString() == "mid")
                                {
                                    liveCoderFrame.bbt3.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) / 60).ToString());
                                    liveCoderFrame.bbt4.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) % 60).ToString());

                                    tag[1] = "B_Timer_Mid"; data[1] = liveCoderFrame.bbt3.Text.Substring(1) + ":" + liveCoderFrame.bbt4.Text;
                                }
                                if (item["파괴된라인"].ToString() == "bot")
                                {
                                    liveCoderFrame.bbt5.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) / 60).ToString());
                                    liveCoderFrame.bbt6.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) % 60).ToString());

                                    tag[1] = "B_Timer_Bot"; data[1] = liveCoderFrame.bbt5.Text.Substring(1) + ":" + liveCoderFrame.bbt6.Text;
                                }
                            }
                            else
                            {
                                if (item["타워위치"].ToString().Contains("1748"))
                                {
                                    liveCoderFrame.bbt7.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) / 60).ToString());
                                    liveCoderFrame.bbt8.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) % 60).ToString());
                                }
                                else if (item["타워위치"].ToString().Contains("2177"))
                                {
                                    liveCoderFrame.bbt9.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) / 60).ToString());
                                    liveCoderFrame.bbt10.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) % 60).ToString());
                                }

                                    
                            }

                            if (TM.isDisplayInhibitorBlue) TM.DisplayInhibitor(liveCoderFrame.bbt1.Text, liveCoderFrame.bbt2.Text, liveCoderFrame.bbt3.Text,
                                liveCoderFrame.bbt4.Text, liveCoderFrame.bbt5.Text, liveCoderFrame.bbt6.Text,
                                liveCoderFrame.bbt7.Text, liveCoderFrame.bbt8.Text, liveCoderFrame.bbt9.Text, liveCoderFrame.bbt10.Text,
                                true);

                        }
                        else
                        {
                            if (item["넥서스타워"].ToString() == "")
                            {
                                if (item["파괴된라인"].ToString() == "top")
                                {
                                    //item["남은시간(초)"]
                                    liveCoderFrame.rbt1.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) / 60).ToString());
                                    liveCoderFrame.rbt2.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) % 60).ToString());

                                    tag[2] = "R_Timer_Top"; data[2] = liveCoderFrame.rbt1.Text.Substring(1) + ":" + liveCoderFrame.rbt2.Text;

                                }
                                else if (item["파괴된라인"].ToString() == "mid")
                                {
                                    liveCoderFrame.rbt3.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) / 60).ToString());
                                    liveCoderFrame.rbt4.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) % 60).ToString());

                                    tag[2] = "R_Timer_Mid"; data[2] = liveCoderFrame.rbt3.Text.Substring(1) + ":" + liveCoderFrame.rbt4.Text;
                                    //tag[2] = "R_Timer_Mid"; data[2] = rbt3.Text.Substring(1) + ":" + rbt4.Text;
                                    //R_Timer_Mid
                                }
                                else if (item["파괴된라인"].ToString() == "bot")
                                {
                                    liveCoderFrame.rbt5.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) / 60).ToString());
                                    liveCoderFrame.rbt6.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) % 60).ToString());

                                    tag[2] = "R_Timer_Bot"; data[2] = liveCoderFrame.rbt5.Text.Substring(1) + ":" + liveCoderFrame.rbt6.Text;
                                }
                            }
                            else
                            {
                                if (item["타워위치"].ToString().Contains("12611"))
                                {
                                    liveCoderFrame.rbt7.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) / 60).ToString());
                                    liveCoderFrame.rbt8.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) % 60).ToString());
                                }
                                else if (item["타워위치"].ToString().Contains("13052"))
                                {
                                    liveCoderFrame.rbt9.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) / 60).ToString());
                                    liveCoderFrame.rbt10.Text = GetTime((Convert.ToUInt32(item["남은시간(초)"].ToString()) % 60).ToString());
                                }
                            }
                            
                               

                            if (TM.isDisplayInhibitorRed) TM.DisplayInhibitor(liveCoderFrame.rbt1.Text, liveCoderFrame.rbt2.Text, liveCoderFrame.rbt3.Text,
                                liveCoderFrame.rbt4.Text, liveCoderFrame.rbt5.Text, liveCoderFrame.rbt6.Text,
                                liveCoderFrame.rbt7.Text, liveCoderFrame.rbt8.Text, liveCoderFrame.rbt9.Text, liveCoderFrame.rbt10.Text,
                                false);

                        }
                    }
                }));
            }
            catch(Exception ex) { }
        }
                
        public void 한타딜량실시간(DataTable 한타딜량선수별)
        {
            try
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    DataTable dt = 한타딜량선수별;

                    if (TM.isDisplayFightRealTime)
                    {
                        if (liveCoderFrame.chkNewDesign.Checked)
                        {
                            TM.DisplayFight(true, "", dt, DC, true);
                        }
                        else
                        {
                            TM.DisplayFight(true, "", dt, DC);
                        }
                        
                    }
                }));
            }
            catch (Exception ex) { }
        }


        int questDone = -1;
        public void 라인퀘스트정보(DataTable 라인퀘스트정보)
        {
            try
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    int isDone = 0;
                    foreach (DataRow dr in 라인퀘스트정보.Rows)
                    {
                        if (Convert.ToBoolean(dr[3].ToString())) isDone++;
                    }

                    if (isDone != questDone)
                    {
                        questDone = isDone;
                        liveCoderFrame.setCheckBox();
                    }

                }));
            }
            catch (Exception ex) { }
        }

        #endregion


        #region 경기설정 (화면 우측)

        private void btnGame_Click(object sender, EventArgs e)
        {
            GameForm gameForm = new GameForm(this);
            gameForm.ShowDialog();

            selectTeamText();
        }

        public void selectTeamText()
        {
            //선택한 팀의 정보를 각 Frame에 입력한다.            
            txtBTeam.Text = DC.BlueLiner.TeamName;
            liveCoderFrame.txtBTeam.Text = DC.BlueLiner.TeamName;
            banPickFrame.txtBTeam1.Text = DC.BlueLiner.TeamName; 

            txtRTeam.Text = DC.RedLiner.TeamName;
            liveCoderFrame.txtRTeam.Text = DC.RedLiner.TeamName;
            banPickFrame.txtRTeam1.Text = DC.RedLiner.TeamName;

            banPickFrame.refreshLines();
            

            //기존에 저장한 방제가 있으면 해당 텍스트를 입력한다
            DC.LoadMatchs();
            var target = DC.Matchs.Find(x => x.BlueTeam == DC.BlueLiner.TeamName && x.RedTeam == DC.RedLiner.TeamName);
            textEdit3.Text = target.MatchNumber;
            if (target.RoomName != null) txtgame.Text = target.RoomName;
        }

        private void btnPlayer_Click(object sender, EventArgs e)
        {
            PlayerForm playerForm = new PlayerForm(this);

            playerForm.ShowDialog();
        }

        private void btnTeam_Click(object sender, EventArgs e)
        {
            TeamForm teamForm = new TeamForm(this);

            teamForm.ShowDialog();
        }

        private void btnRoom_Click(object sender, EventArgs e)
        {
            MatchForm matchForm = new MatchForm(this);

            matchForm.ShowDialog();
        }

        #endregion


        #region GameStart, GameKey, TimerData

        Timer mTimer = new Timer();
        Timer TimerGameTime = new Timer();


        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnStart.Text == "START")
                {
                    if (mTime.Text == "" || sTime.Text == "") return;
                    int time = (Convert.ToInt32(mTime.Text) * 60) + Convert.ToInt32(sTime.Text);

                    //재연결 추가
                    DataManager.getInstance().requestServerForUpdate(txtip.Text.Trim(), txtgame.Text.Trim(), isTest);
                    DataManager.getInstance().IsupdateWorkersWork = true;

                    DataManager.getInstance().setGameTime(time);
                    DataManager.getInstance().setCallback(this);
                    DataManager.getInstance().timerStart();


                    //btnMody.Enabled = false;
                    btnStart.Appearance.BackColor = Color.FromArgb(255, 255, 0);
                    btnStart.Text = "STOP";

                    TimerGameTime.Start();
                }
                else
                {
                    DataManager.getInstance().timerStop();
                    btnStart.Appearance.BackColor = Color.Transparent;
                    btnStart.Text = "START";

                    TimerGameTime.Stop();
                }
            }
            catch(Exception ex) { }
            
        }

        private void chkGameKey_CheckedChanged(object sender, EventArgs e)
        {
            if (chkGameKey.Checked)
            {
                labelControl4.Visible = false;
                txtCode.Visible = true;
                btnConnect.Visible = true;
            }
            else
            {
                labelControl4.Visible = true;
                txtCode.Visible = false;
                btnConnect.Visible = false;
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            string file = Environment.CurrentDirectory + @"\Data\en_US\champion.json";
            var info = new FileInfo(file);
            /*
            if (info.LastWriteTime.Year.ToString() == "2025")
            {
                Log("서버 연결 실패 - 데이터 양식 Error", LogType.Error);
                return;
            }
            */

            if (sender != null)
            {
                btn_AllClear_Click(null, null);
            }

            if (sender == null) ConnectGameKey(true);
            else ConnectGameKey();
        }

        
        public void ConnectGameKey(bool isAuto = false)
        {
            try
            {
                string ip = string.Empty;

                if (isAuto || MessageBox.Show("게임키를 설정 하시겠습니까?", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    ip = txtip.Text;

                    DataManager.getInstance().setCallback(this);
                    DataManager.getInstance().IsupdateWorkersWork = true;
                    DataManager.getInstance().mPlatformGameID = txtCode.Text;
                    DataManager.getInstance().isNewBanPick = chk운영툴.Checked;
                    //bool isTest = true;

                    DBDefine.서버의답변 돌아온서버의답변 = DataManager.getInstance().requestServerForUpdateGameKey(txtip.Text.Trim(), txtCode.Text.Trim(), isTest);

                    if (mTimer.Enabled) mTimer.Stop(); 

                    switch (돌아온서버의답변)
                    {
                        case DBDefine.서버의답변.방을찾았고업데이트를시작함:
                            if (!isAuto)
                            {
                                lblConnectionData.BackColor = Color.FromArgb(0, 192, 0);
                                //연결완료
                                Log("서버 연결 성공", LogType.Normal);
                            }
                            m_livestats = true;
                            break;
                        case DBDefine.서버의답변.이미방을업데이트중임:
                            if (!isAuto)
                            {
                                lblConnectionData.BackColor = Color.FromArgb(0, 192, 0);

                                //업데이트되는중
                                Log("서버 연결 성공 - 업데이트 되는 중", LogType.Normal);
                            }
                            m_livestats = true;
                            break;
                        case DBDefine.서버의답변.방을못찾아서업데이트를못함:
                            if (!isAuto)
                            {
                                lblConnectionData.BackColor = Color.FromArgb(192, 0, 0);
                                //방없음
                                Log("서버 연결 실패 - 방을 찾을 수 없습니다.", LogType.Error);
                            }
                            m_livestats = false;
                            break;
                        case DBDefine.서버의답변.명령이틀림:
                            if (!isAuto)
                            {
                                lblConnectionData.BackColor = Color.FromArgb(192, 0, 0);
                                //일어나지 않을 버그
                                Log("서버 연결 실패 - 일어나지 않을 버그?!", LogType.Error);
                            }
                            m_livestats = false;
                            break;
                        case DBDefine.서버의답변.서버와의연결이이상함:
                            if (!isAuto)
                            {
                                lblConnectionData.BackColor = Color.FromArgb(192, 0, 0);
                                //서버가 응답이 없음(꺼져있거나 등등)
                                Log("서버 연결 실패 - 서버 응답이 없습니다", LogType.Error);
                            }
                            m_livestats = false;
                            break;

                    }
                     

                    if (m_livestats)
                    {
                        mTimer.Interval = 1000;
                        mTimer.Tick -= dataTick;
                        mTimer.Tick += dataTick;
                        mTimer.Start();
                    }
                }
            }
            catch (Exception ex) { }
        }


        int ObjectControlCount = 0;
        int ObjectTower = 0;
        int forReCoonection = 0;
        private void dataTick(object d, EventArgs e)
        {
            //Console.WriteLine("datatick!" + DateTime.Now.ToString() );

            try
            {
                forReCoonection++;

                if (forReCoonection == 5)
                {
                    forReCoonection = 0;
                    if (TimerGameTime.Enabled)
                    {
                        if (chkGameKey.Checked) btnConnect_Click(null, null);
                        else simpleButton9_Click(null, null);
                    }
                }

                string bdragon = string.Empty;
                string rdragon = string.Empty;

                //첫킬 파악
                /*
                if (liveCoderFrame.R_FirstBlood.Tag.ToString().Contains("_0") && liveCoderFrame.B_FirstBlood.Tag.ToString().Contains("_0"))
                {
                    DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.킬뎃어시).Tables[0];

                    int countOfKill1 = 0;
                    bool isBlue = true;

                    foreach(DataRow row in dt.Rows)
                    {
                        try
                        {
                            int killCount = Convert.ToInt32(row.ItemArray[3].ToString());
                            if (killCount > 0)
                            {
                                countOfKill1 = countOfKill1 + killCount;
                                if (row.ItemArray[0].ToString() == "블루") isBlue = true;
                                else isBlue = false;
                            }
                        }
                        catch(Exception ex) { }
                        
                        row.ToString();
                    }

                    if (countOfKill1 == 1)
                    {
                        if (isBlue) liveCoderFrame.B_FirstBlood.Tag = liveCoderFrame.B_FirstBlood.Tag.ToString().Replace("_0", "_1");
                        else liveCoderFrame.R_FirstBlood.Tag = liveCoderFrame.R_FirstBlood.Tag.ToString().Replace("_0", "_1");

                        liveCoderFrame.set무력행사Image();
                    }
                }
                */
                //타워 골드 획득 정보
                {
                    DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.타워골드데이터).Tables[0];

                    liveCoderFrame.골드획득정보디버깅(dt);
                }

                //용 획득
                if (!liveCoderFrame.ck2.Checked)
                {
                    DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.오브젝트킬).Tables[0];

                    if (ObjectControlCount != dt.Rows.Count)
                    {                         
                        liveCoderFrame.Dragon_Load(dt);
                        ObjectControlCount = dt.Rows.Count;

                        if (TM.isDisplayDragon) TM.DisplayDragon();
                    } 
                }

                //타워
                if (!liveCoderFrame.chkTower.Checked)
                {
                    //Console.WriteLine("A");
                    DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.타워철거전체).Tables[0];

                    List<DataRow> drs = new List<DataRow>();
                    int sec = Convert.ToInt32(mTime.Text) * 60 + Convert.ToInt32(sTime.Text);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (sec < Convert.ToInt32(dt.Rows[i][1]))
                        {
                            drs.Add(dt.Rows[i]);
                        }
                    }

                    foreach(var dr in drs)
                    {
                        dt.Rows.Remove(dr);
                    }
                    

                    //Console.WriteLine("B");
                    if (ObjectTower != dt.Rows.Count)
                    {
                        //dataGridView1.DataSource = dt;

                        int blueTower = 0;
                        int redTower = 0;

                        foreach(DataRow dr in dt.Rows)
                        {
                            if (dr[4].ToString().Equals("turret"))
                            {
                                if (dr[0].ToString().Equals("블루")) blueTower++;
                                else redTower++;
                            }
                        }

                        liveCoderFrame.BT.Text = blueTower.ToString();
                        liveCoderFrame.RT.Text = redTower.ToString();

                        ObjectTower = dt.Rows.Count;

                        /*
                        if (TM.isDisplayTower) TM.DisplayTower(blueTower.ToString(), redTower.ToString());

                        if (liveCoderFrame.R_Turret.Tag.ToString().Contains("_0") && liveCoderFrame.B_Turret.Tag.ToString().Contains("_0"))
                        {
                            if (blueTower == 0 && redTower == 1)
                            {
                                liveCoderFrame.B_Turret.Tag = liveCoderFrame.B_Turret.Tag.ToString().Replace("_0", "_1");
                                liveCoderFrame.set무력행사Image();
                            }
                            else if (redTower == 1 && blueTower == 0)
                            {
                                liveCoderFrame.R_Turret.Tag = liveCoderFrame.R_Turret.Tag.ToString().Replace("_0", "_1");
                                liveCoderFrame.set무력행사Image();
                            }
                        }
                        */
                    }
                }
                    

                //골드
                if (TM.isDisplayGold)
                {
                    DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.현재골드량선수).Tables[0];
                    TM.DisplayGold(dt, DC, isT1Home, resultFrame.lblBlueColor.BackColor, resultFrame.lblRedColor.BackColor);
                }
                //딜
                if (TM.isDisplayDeal)
                {
                    DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.현재데미지량선수).Tables[0];
                    TM.DisplayDeal(dt, DC);
                }


                //버그 수정용
                if (liveCoderFrame.chkDragonBugFix.Checked)
                {
                    TextEdit txtMIN = liveCoderFrame.dt1;
                    TextEdit txtSEC = liveCoderFrame.dt2;

                    if (txtSEC.Text != "LIVE")
                    {
                        int sec = Convert.ToInt32(txtMIN.Text) * 60 + Convert.ToInt32(txtSEC.Text);
                        if (sec == 0)
                        {
                            txtSEC.Text = "LIVE";
                        }
                        else
                        {
                            sec--;

                            txtMIN.Text = GetTime((sec / 60).ToString());
                            txtSEC.Text = GetTime((sec % 60).ToString());
                        }

                        if (txtMIN.Text == "00" && txtSEC.Text == "00")
                        {
                            txtSEC.Text = "LIVE";
                        }
                    }
                } 
            }
            catch (Exception)
            {

            }
        }



        #endregion


        #region 룬페이지

        public DataTable getRunData()
        {
            try
            {
                return DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.룬데이터).Tables[0];
            }
            catch(Exception ex) {
                return null;
            }
            
        }

        #endregion


        #region 골드 / 데미지

        
        //누적골드 
        public void AccumulatedGold()
        {
            try
            {
                DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.현재골드량선수).Tables[0];
                TM.DisplayGold(dt, DC, isT1Home, resultFrame.lblBlueColor.BackColor, resultFrame.lblRedColor.BackColor);
            }
            catch(Exception ex) { }
            
        }


        
        Series[] series = new Series[4];
        
        ChartControl rangeAreaChart = new ChartControl();
        string subKey = @"SOFTWARE\CI";
        string imgFileName = "CI";  //파일명
        string imgFileExtension = ".png"; //확장자
        string imgPath = Environment.CurrentDirectory + @"\Chart\";
        int imgCount = 0;
        public void File_Delete()
        {
            //기존에 저장된 인덱스 불러오기            
            RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey); //Registry 키값 불러오기
            if (key.GetValue("CI") != null) //값이 있는 경우
            {
                imgCount = Convert.ToInt32(key.GetValue("CI").ToString()); //해당 인덱스를 저장

                for (int i = 1; i < imgCount; i++) //이전 인덱스 파일들 삭제
                {
                    System.IO.FileInfo file_info = new System.IO.FileInfo(imgPath + imgFileName + i + imgFileExtension);

                    try
                    {
                        file_info.Delete();
                    }
                    catch (System.IO.IOException)
                    {
                        // handle exception
                    }
                }
            }
            key.Close();
        }

        public bool isT1Home = false;
        
        public void GoldGraph(bool isForGoldGraph)
        { 
            try
            {
                DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.골드차이팀).Tables[0];

                int row = dt.Rows.Count - 1;

                //현재 시각 대비하여 데이터를 당겨 오는 로직을 추가한다.
                int nowtime = (Convert.ToInt32(mTime.Text) * 60 + Convert.ToInt32(sTime.Text));
                for (int i = 0; i < row; i++)
                {
                    if (nowtime <= Convert.ToInt32(dt.Rows[i][5].ToString()))
                    {
                        row = i;
                        break;
                    }
                }
                

                double min = 0.0;
                double max = 0.0;
                string data = string.Empty;

                for (int i = 0; i < row; i++)
                {
                    double iValue = Convert.ToDouble(dt.Rows[i][2].ToString());

                    
                    {
                        if (min > iValue) min = iValue;
                        if (max < iValue) max = iValue;
                    }

                    data += dt.Rows[i][2].ToString() + ",";
                }

                string[] Result = data.Split(',');

                series[0] = new Series("Series 1", ViewType.RangeArea);
                series[1] = new Series("Series 2", ViewType.RangeArea);
                series[2] = new Series("Series 3", ViewType.RangeArea);

                //데이터 Setting

                for (int i = 0; i < Result.Length - 1; i++)
                {
                    if (Convert.ToDouble(Result[i]) < 0)
                    {
                        series[1].Points.Add(new SeriesPoint(i, Convert.ToDouble(Result[i]), 0));
                        series[0].Points.Add(new SeriesPoint(i, 0, 0));
                        series[2].Points.Add(new SeriesPoint(i, 0, 0));
                    }
                    else if (Convert.ToDouble(Result[i]) > 0)
                    {
                        series[1].Points.Add(new SeriesPoint(i, 0, 0));
                        series[0].Points.Add(new SeriesPoint(i, 0, Convert.ToDouble(Result[i])));
                        series[2].Points.Add(new SeriesPoint(i, 0, 0));
                    }
                    else
                    {
                        series[0].Points.Add(new SeriesPoint(i, 0, 0));
                        series[1].Points.Add(new SeriesPoint(i, 0, 0));
                        series[2].Points.Add(new SeriesPoint(i, 0, 0));
                    }

                }

                chartControl1.Series.Clear();
                // Add a series to the chart.
                chartControl1.Series.Add(series[0]);
                chartControl1.Series.Add(series[1]);
                chartControl1.Series.Add(series[2]);

                // Access the view-type-specific options of the series.
                ((RangeAreaSeriesView)series[0].View).Transparency = 0;
                ((RangeAreaSeriesView)series[1].View).Transparency = 0;


                if (isT1Home)
                {
                    ((RangeAreaSeriesView)series[0].View).Color = resultFrame.lblBlueColor.BackColor;
                    ((RangeAreaSeriesView)series[1].View).Color = resultFrame.lblRedColor.BackColor;
                }
                else
                {
                    ((RangeAreaSeriesView)series[0].View).Color = Color.FromArgb(55, 73, 235);
                    ((RangeAreaSeriesView)series[1].View).Color = Color.FromArgb(255, 47, 79);
                }
                


                // Access the type-specific options of the diagram.
                ((XYDiagram)chartControl1.Diagram).AxisX.GridLines.Visible = false;
                ((XYDiagram)chartControl1.Diagram).AxisY.GridLines.Visible = false;
                //((XYDiagram)chartControl1.Diagram).AxisX.GridLines.

                ((XYDiagram)chartControl1.Diagram).AxisY.WholeRange.MinValue = min;  //최소
                ((XYDiagram)chartControl1.Diagram).AxisY.WholeRange.MaxValue = max;  //최대 


                chartControl1.CrosshairEnabled = DefaultBoolean.False;



                XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
                //diagram.AxisY.WholeRange.Auto = true;      // y축 범위 자동변경 설정             
                //diagram.AxisX.WholeRange.SideMarginsValue = 5;


                //기준선 0
                ConstantLine zeroLine = new ConstantLine();
                zeroLine.Color = Color.Black;
                zeroLine.AxisValue = 0;
                zeroLine.ShowInLegend = false;
                diagram.AxisY.ConstantLines.Add(zeroLine);  // y값 0인 x축 생성                                                   
                diagram.EnableAxisXScrolling = true;   //스크롤과 줌은 절대             
                diagram.EnableAxisXZooming = true; //true로 하지않도록 한다.  

                //chartControl1.PaletteBaseColorNumber = 1;
                File_Delete();

                imgCount++;
                RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey);
                key.SetValue("CI", imgCount);
                key.Close();

                //기존에 저장된 인덱스 이미지 삭제하기                   
                System.IO.FileInfo file_info = new System.IO.FileInfo(imgPath + imgFileName + (imgCount - 1) + imgFileExtension);

                string path = imgPath + imgFileName + imgCount + imgFileExtension;

                //string FileName = RES_FOLDER_PATH + "Chart1.png";
                chartControl1.ExportToImage(path, ImageFormat.Png);
                int time = Convert.ToInt32(dt.Rows[row - 1][5].ToString());

                if (isForGoldGraph) TM.DisplayGoldGraph(time, row, max, min, path);
                else TM.ForResultGold = new string[] { time.ToString(), row.ToString(), max.ToString(), min.ToString(), path };
            }
            catch (Exception ex)
            {
                //Log(ex.Message, LogType.Error);
            } 
        }
         

        public void Deal()
        {
            try
            {
                DataTable dt = DataManager.getInstance().라이브데이터요청(DBDefine.요청데이터분류.현재데미지량선수).Tables[0];

                TM.DisplayDeal(dt, DC);
            }
            catch(Exception ex) { }
            
        }
         

        #endregion



        #region 메인 레이어 버튼 설정
        public Color colorMainLayer = Color.FromArgb(255, 128, 191);
        public SimpleButton beforeBtn = null;
        public bool MainLayerButton(SimpleButton sender)
        {
            if (beforeBtn != null)
            {
                bool isEquals = beforeBtn.Equals(sender);

                TM.isDisplayBanPick = false;
                if (TM.timer.Enabled) TM.timer.Stop();
                TM.isDisplayGold = false;
                TM.isTowerGoldDisplaying = false;
                TM.isDisplayGoldGraph = false;
                TM.isDisplayDeal = false;
                TM.isDisplayFight = false;
                TM.isDisplayFightRealTime = false;
                TM.isDisplayTowerGold = false;
                banPickFrame.TimerSwitch(false);



                if (sender == beforeBtn || sender == null)
                {
                    if (beforeBtn.Name == "btnBanPick")
                    {
                        TM.Out(2); 
                    }
                    TM.Out(1);
                    TM.UnLoadMain();
                }

                beforeBtn.Appearance.BackColor = Color.Transparent;
                beforeBtn = null;

                


                if (isEquals) return false;
            }

            if (sender != null) sender.Appearance.BackColor = colorMainLayer;
            beforeBtn = sender;

            return true;

        }

        #endregion



        public string[] GetTitle() => new string[] { MatchText.Text + " " + textEdit3.Text, "GAME " + comboGame.SelectedItem.ToString(), textpatch.Text };  //"PATCH " + textpatch.Text };

        public Bitmap imageReSize(int w, int h, string path)
        {
            string RES_FOLDER_PATH = Environment.CurrentDirectory + @"\Res\";

            path = path.Replace("Legend:", "Legend");

            try
            {
                if (path == "" || !File.Exists(path))
                {
                    //Log(path, LogType.Error);
                    path = RES_FOLDER_PATH + "CLEAR.png";
                }

                path = path.Replace("Legend:", "Legend");

                Bitmap sourceImage = new Bitmap(path);

                // 사이즈가 변경된 이미지
                int width = w;
                int height = h;
                Size resize = new Size(width, height);
                Bitmap resizeImage = new Bitmap(sourceImage, resize);
                resizeImage.Tag = path;
                //resizeImage.Tag = 

                return resizeImage;
            }

            catch (Exception ex)
            {
                Log("이미지 로드 에러.." + path, LogWriter.LogType.Error);
                return null;
            }
        }

        
        public void colorSave(string target, Color color)
        {
            RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey);
            key.SetValue(target, color.ToArgb());
            key.Close();
        }

        private void textpatch_EditValueChanged(object sender, EventArgs e)
        {
            if (sender == textpatch)
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey);
                key.SetValue("version", textpatch.Text);
                key.Close();
            }
            else if (sender == txtgame)
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey);
                key.SetValue("game", txtgame.Text);
                key.Close();
            }
            else if (sender == txtCode)
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey);
                key.SetValue("code", txtCode.Text);
                key.Close();
            }
            else if (sender == txtip)
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey);
                key.SetValue("IP", txtip.Text);
                key.Close();
            }
            else if (sender == MatchText)
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey);
                key.SetValue("Match", MatchText.Text);
                key.Close();
            }
            else if (sender == textEdit3)
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey);
                key.SetValue("textEdit3", textEdit3.Text);
                key.Close();
            }
            else if (sender == txtOutFrame)
            {
                try
                {
                    int outFrame = Convert.ToInt32(txtOutFrame.Text);
                    TM.FadeInSec = outFrame;

                    RegistryKey key = Registry.CurrentUser.CreateSubKey(subKey);
                    key.SetValue("OutFrame", txtOutFrame.Text);
                    key.Close();
                }
                catch (Exception ex)
                {
                    Log("아웃 프레임 숫자 변경 중 에러발생", LogType.Error);
                }
            }
        }

        bool isTest = true;
        bool m_livestats = false;
        private void simpleButton9_Click(object sender, EventArgs e)
        {
            try
            { 
                if (sender != null)
                {
                    //DataManager.getInstance().resetDBAddress(txtip.Text.Trim());
                    //btn_AllClear_Click(null, null);
                }

                DataManager.getInstance().isNewBanPick = chk운영툴.Checked;
                

                //bool isTest = true;
                DBDefine.서버의답변 돌아온서버의답변 = DataManager.getInstance().requestServerForUpdate(txtip.Text.Trim(), txtgame.Text.Trim(), isTest);

                //if (sender == null) Log("자동 재연결 진행중", LogType.Normal);
                string file = Environment.CurrentDirectory +  @"\Data\en_US\champion.json";
                var info = new FileInfo(file);
                /*
                if (info.LastWriteTime.Year.ToString() == "2025")
                {
                    Log("서버 연결 실패 - 데이터 양식 Error", LogType.Error);
                    return;
                }
                */
                


                switch (돌아온서버의답변)
                {
                    case DBDefine.서버의답변.방을찾았고업데이트를시작함:
                        if (sender != null)
                        {
                            lblConnectionData.BackColor = Color.FromArgb(0, 192, 0);
                            //연결완료
                            Log("서버 연결 성공", LogType.Normal);
                        }
                        m_livestats = true;
                        break;
                    case DBDefine.서버의답변.이미방을업데이트중임:
                        if (sender != null)
                        {
                            lblConnectionData.BackColor = Color.FromArgb(0, 192, 0);

                            //업데이트되는중
                            Log("서버 연결 성공 - 업데이트 되는 중", LogType.Normal);
                        }
                        m_livestats = true;
                        break;
                    case DBDefine.서버의답변.방을못찾아서업데이트를못함:
                        if (sender != null)
                        {
                            lblConnectionData.BackColor = Color.FromArgb(192, 0, 0);
                            //방없음
                            Log("서버 연결 실패 - 방을 찾을 수 없습니다.", LogType.Error);
                        }
                        m_livestats = false;
                        break;
                    case DBDefine.서버의답변.명령이틀림:
                        if (sender != null)
                        {
                            lblConnectionData.BackColor = Color.FromArgb(192, 0, 0);
                            //일어나지 않을 버그
                            Log("서버 연결 실패 - 일어나지 않을 버그?!", LogType.Error);
                        }
                        m_livestats = false;
                        break;
                    case DBDefine.서버의답변.서버와의연결이이상함:
                        if (sender != null)
                        {
                            lblConnectionData.BackColor = Color.FromArgb(192, 0, 0);
                            //서버가 응답이 없음(꺼져있거나 등등)
                            Log("서버 연결 실패 - 서버 응답이 없습니다", LogType.Error);
                        }
                        m_livestats = false;
                        break;

                }

                DataManager.getInstance().IsupdateWorkersWork = true;

                if (m_livestats)
                {       
                    mTimer.Interval = 1000;
                    mTimer.Tick -= dataTick; 
                    mTimer.Tick += dataTick;
                    mTimer.Start();
                }
            }
            catch(Exception ex) { }
        }

        private void btn_AllClear_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("데이터를 초기화 하시겠습니까?", "Data Initation", MessageBoxButtons.YesNo) == DialogResult.No)
                    return;
                 
                if (btnStart.Text != "START")
                {
                    btnStart_Click(null, null);
                }

                DataManager.getInstance().timerStop();
                DataManager.getInstance().requestServerForUpdateRemoveAll(txtip.Text.Trim());
                lblConnectionData.BackColor = Color.FromArgb(192, 0, 0);

                for (int i = 0; i < 5; i++)
                {
                    Liner liner = DC.BlueLiner.GetLiner(i);
                    liner.champ = "";
                    liner.champID = -1;
                    liner.ban = "";
                    liner.state = "";
                    DC.BlueLiner.SetLiner(i, liner);

                    liner = DC.RedLiner.GetLiner(i);
                    liner.champ = "";
                    liner.champID = -1;
                    liner.ban = "";
                    liner.state = "";
                    DC.RedLiner.SetLiner(i, liner);
                }

                mTime.Text = "00";
                sTime.Text = "00";

                //모든 값 초기화
                banPickFrame.AllClear();
                runePageFrame.AllClear();
                liveCoderFrame.AllClear();
                resultFrame.AllClear();

                questDone = -1;

                TM.UnLoadAll();
            }
            catch (Exception ex) { }
        }

        private void btnDsiplayClearAll_Click(object sender, EventArgs e)
        {
            try
            {
                liveCoderFrame.AllOut();
                MainLayerButton(null);
            }
            catch(Exception ex)
            {
                Log(ex.Message, LogType.Error);
            }
            
        }

        private void pictureEdit1_MouseClick(object sender, MouseEventArgs e)
        {
            //return;
            //TM.DisplayTest(); 
        }

        private void pictureEdit3_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                string rtn = DataManager.getInstance().requestServerForGameInfo(txtip.Text);

                if (rtn.Contains(Environment.NewLine))
                {
                    rtn = rtn.Replace(Environment.NewLine, "^");
                    txtgame.Text = rtn.Split('^')[0];
                    txtCode.Text = rtn.Split('^')[1];
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {

        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            isTest = checkEdit1.Checked;
        }

        private void toggleSwitch1_Toggled(object sender, EventArgs e)
        { 
                DataManager.getInstance().밴데이터만들기(toggleSwitch1.IsOn); 
        }

        public bool getIsRedStart => toggleSwitch1.IsOn;
    }
}
