//ライセンス情報はAgeOnフォルダのLISENCEフォルダを参照してください
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

using nispi.Menu;
using nispi.controlclass;

namespace nispi
{
    class MapControlView : DrawToMap
    {
        //public PanelParts panelInfoParts;
        public PanelParts panelCommandParts;
        public PanelParts panelMapParts;
        //public Panel panelMain;
        public TabPageExParts tabPageParts;

        public string frontFile;
        public string backFile;

        public PictureBoxParts picBoxParts;

        public Bitmap eternalFillBitmap;
        public Bitmap eternalPointBitmap;

        public Bitmap synthesisBitmap;
        public Bitmap fillBitmap;
        public Bitmap pointBitmap;

        public Bitmap backBitmap;

        public ButtonParts surviveImageButtonParts;
        public ButtonParts resetButtonParts;
        public ButtonParts reload_buttonParts;

        //時間抽出関係
        public WithInCBoxParts withInCBoxParts;
        //public ComboBox kakoLogCBox;
        public ButtonParts pinPointDateButtonParts;
        public ButtonParts timeOffButtonParts;

        public int containKakoLog = 0;
        public int withInNum = 0;
        public string pinPointData = "";
        public string pinPointJPDate = "";

        public KokkaData beforeKokkaData = null;

        public Dictionary<string, KenData> kenDic = new Dictionary<string, KenData>();

        //public Stopwatch sw = new Stopwatch();
        bool analysisDataDownload = false;
        
        public ToolTipParts toolTipParts = ToolTipPartsManager.Pop();

        public string fileName = "subject_info";
        public Dictionary<string, KokkaData> nameDic;
        public Dictionary<string, KokkaData> colorDic;

        public MapControlView(string text, string frontFile, string backFile, Dictionary<string, KokkaData> nameDic, Dictionary<string, KokkaData> colorDic, int width, int height)
        {
            this.frontFile = frontFile;
            this.backFile = backFile;

            this.nameDic = nameDic;
            this.colorDic = colorDic;

            eternalFillBitmap = new Bitmap(
                Const.CurrentDir + Path.DirectorySeparatorChar + "data" + Path.DirectorySeparatorChar + this.frontFile);
            eternalPointBitmap = new Bitmap(eternalFillBitmap.Width, eternalFillBitmap.Height);

            Graphics g = Graphics.FromImage(eternalPointBitmap);
            g.FillRectangle(Brushes.Black, g.VisibleClipBounds);
            g.Dispose();

            fillBitmap = new Bitmap(eternalFillBitmap);
            pointBitmap = new Bitmap(eternalPointBitmap);

            backBitmap = new Bitmap(Const.CurrentDir + Path.DirectorySeparatorChar + "data" + Path.DirectorySeparatorChar + backFile);

            synthesisBitmap = ImageUtil.SynthesisImage(fillBitmap, pointBitmap);

            picBoxParts = PictureBoxPartsManager.Pop();
            picBoxParts.Image = synthesisBitmap;// GetImageFileData();

            picBoxParts.MouseMove += new MouseEventHandler(picBox_Kokka_MouseMove);

            picBoxParts.MouseClick += new MouseEventHandler(picBox_MouseClick);

            picBoxParts.Location = new Point(0, 0);
            picBoxParts.Size = new Size(fillBitmap.Width, fillBitmap.Height);
            picBoxParts.MouseHover += new EventHandler(picBox_MouseHover);


            tabPageParts = TabPageExPartsManager.Pop();
            tabPageParts.Name = text;
            tabPageParts.Text = "";


            panelMapParts = PanelPartsManager.Pop();
            //panelMapParts.SetAnchor4();
            panelMapParts.Location = new Point(0, 31);
            panelMapParts.BackColor = Color.FromArgb(153, 217, 234);
            //panelMap.Dock = DockStyle.Fill;
            //panelMapParts.Size = new Size(Const.mapForm.MapControlTabControlParts.Size.Width,
            //    Const.mapForm.MapControlTabControlParts.Size.Height - 140);

            panelCommandParts = PanelPartsManager.Pop();
            //panelMapParts.SetAnchor4();
            panelCommandParts.Location = new Point(0, 0);
            //panelCommandParts.Size = new Size(Const.mapForm.mainSplitContainerParts.Panel2_Width,
            //    Const.mapForm.mainSplitContainerParts.Panel2_Height - 60);

            //生存スレに関して整理された画像データを得る
            surviveImageButtonParts = ButtonPartsManager.Pop();
            //surviveImageButtonParts.SetAnchorTopLeft();
            surviveImageButtonParts.Location = new Point(1, 1);
            surviveImageButtonParts.Name = "surviveImageButton";
            surviveImageButtonParts.Size = new Size(120, 26);
            surviveImageButtonParts.Text = "生存スレを表示";
            //surviveImageButton.Image = System.Drawing.Image.FromFile("reload.png");
            surviveImageButtonParts.Click += new EventHandler(surviveImageButton_MouseClick);
            
            //表示のリセット
            resetButtonParts = ButtonPartsManager.Pop();
            //resetButtonParts.SetAnchorTopLeft();
            resetButtonParts.Location = new Point(125, 1);
            resetButtonParts.Name = "resetButton";
            resetButtonParts.Size = new Size(70, 26);
            resetButtonParts.Text = "リセット";
            resetButtonParts.Click += new EventHandler(resetButton_MouseClick);

            //リロードボタンの設定
            reload_buttonParts = ButtonPartsManager.Pop();
            //reload_buttonParts.SetAnchorTopLeft();
            reload_buttonParts.Location = new Point(205, 1);
            reload_buttonParts.Name = "search";
            reload_buttonParts.Size = new System.Drawing.Size(26, 26);
            Bitmap bitmap2 = new Bitmap(Resources.reload);
            bitmap2.MakeTransparent(Color.White);
            reload_buttonParts.Image = bitmap2;
            reload_buttonParts.Click += new EventHandler(reload_button_Click);
            //コンボボックス
            /*kakoLogCBox = new ComboBox();
            kakoLogCBox.Anchor = (System.Windows.Forms.AnchorStyles.Top) | (System.Windows.Forms.AnchorStyles.Left);
            kakoLogCBox.Location = new System.Drawing.Point(230, 1);
            kakoLogCBox.Name = "kakoLog";
            kakoLogCBox.Size = new System.Drawing.Size(100, 26);
            kakoLogCBox.TabIndex = 0;

            kakoLogCBox.DropDownStyle = ComboBoxStyle.DropDownList;
            kakoLogCBox.Items.Add("生存スレのみ");
            kakoLogCBox.Items.Add("過去ログ含む");
            kakoLogCBox.SelectedIndex = 0;
            kakoLogCBox.SelectedIndexChanged += new EventHandler(kakoLogCBox_MouseClick);*/

            //コンボボックス
            withInCBoxParts = WithInCBoxPartsManager.Pop();
            //withInCBoxParts.SetAnchorTopLeft();
            withInCBoxParts.Location = new Point(325, 1);
            withInCBoxParts.Name = "withIn";
            withInCBoxParts.Size = new Size(110, 26);
            withInCBoxParts.SelectedIndexChanged += new EventHandler(withInCBox_MouseClick);

            //日時指定ボタンの設定
            pinPointDateButtonParts = ButtonPartsManager.Pop();
            pinPointDateButtonParts.Location = new Point(440, 1);
            pinPointDateButtonParts.Name = "pinPointDateButtonParts";
            pinPointDateButtonParts.Size = new Size(26, 26);
            pinPointDateButtonParts.Image = Resources.calendar;
            pinPointDateButtonParts.SetToolTip("日にちを指定");

            pinPointDateButtonParts.Click += new EventHandler(pinPointDateButton_MouseClick);

            timeOffButtonParts = ButtonPartsManager.Pop();
            //timeOffButtonParts.SetAnchorTopLeft();
            timeOffButtonParts.Location = new Point(470, 1);
            timeOffButtonParts.Name = "timeOffButton";
            timeOffButtonParts.Text = "リセット";
            timeOffButtonParts.Size = new System.Drawing.Size(60, 26);
            timeOffButtonParts.Click += new EventHandler(timeOffButton_MouseClick);

            Const.mapForm.MapControlTabControlParts.AddControl(tabPageParts);

            panelCommandParts.AddControl(surviveImageButtonParts);
            panelCommandParts.AddControl(resetButtonParts);
            //panelCommandParts.AddControl(panelInfoParts);
            //tabPage.Controls.Add(kakoLogCBox);
            panelCommandParts.AddControl(withInCBoxParts);
            panelCommandParts.AddControl(pinPointDateButtonParts);
            panelCommandParts.AddControl(timeOffButtonParts);

            tabPageParts.AddControl(panelMapParts);
            panelMapParts.AddControl(picBoxParts);
            tabPageParts.AddControl(panelCommandParts);

            tabPageParts.Text = text;

            //panelMap.Size = new Size(FormShowStyle.worldMapSC1.Panel2.Size.Width/2, FormShowStyle.worldMapSC1.Panel2.Size.Height - 30);
            surviveImageButtonParts.SetToolTip("生存スレッドを表示");

        }

        private void reload_button_Click(object sender, EventArgs e)
        {
            MapMainFormConst.getScreeningData.StartScreening();
        }

        private void picBox_MouseHover(object sender, EventArgs e)
        {
            if (Const.mapForm.mapMainForm.ContainsFocus == true)
            {
                panelMapParts.Focus();
            }
        }

        public void withInCBox_MouseClick(object sender, EventArgs e)
        {
            Const.form.mainForm.SetWaitCursor();

            //pinPointDateButtonParts.Text = "日時指定";
            this.pinPointJPDate = "";
            
            GetScreeningImage getScreeningImage = new GetScreeningImage(frontFile, fileName, nameDic, colorDic);
            BitmapSets bitmapSets = getScreeningImage.GetSurviveThreadImage(0, withInCBoxParts.GetTimeStructure(), "");

            if (bitmapSets != null)
            {
                fillBitmap.Dispose();
                pointBitmap.Dispose();
                fillBitmap = bitmapSets.fillBitmap;
                pointBitmap = bitmapSets.pointBitmap;

                synthesisBitmap = ImageUtil.SynthesisImage(fillBitmap, pointBitmap);
                this.picBoxParts.Image.Dispose();
                this.picBoxParts.Image = synthesisBitmap;
            }

            GetScreeningIndex getScreeningIndex = new GetScreeningIndex(frontFile, fileName, nameDic, colorDic);
            getScreeningIndex.GetSurviveThreadIndex(0, withInCBoxParts.GetTimeStructure(), "");

            Const.form.mainForm.ReSetWaitCursor();
        }

        public void pinPointDateButton_MouseClick(object sender, EventArgs e)
        {
            try
            {
                withInCBoxParts.SelectedIndexChanged -= new EventHandler(withInCBox_MouseClick);
                withInCBoxParts.SelectedIndex = 0;
                withInCBoxParts.SelectedIndexChanged += new EventHandler(withInCBox_MouseClick);

                CalendarInMapControlView calendarInBoardView = new CalendarInMapControlView(0, Cursor.Position, this);
            }
            catch (System.Exception ex)
            {
                //Const.debugForm.OutPutDebug("Map", ex);
            }
        }

        public void timeOffButton_MouseClick(object sender, EventArgs e)
        {
            Const.form.mainForm.SetWaitCursor();

            withInCBoxParts.SelectedIndexChanged -= new EventHandler(withInCBox_MouseClick);
            withInCBoxParts.SelectedIndex = 0;
            withInCBoxParts.SelectedIndexChanged += new EventHandler(withInCBox_MouseClick);

            /*kakoLogCBox.SelectedIndexChanged -= new EventHandler(kakoLogCBox_MouseClick);
            kakoLogCBox.SelectedIndex = 0;
            kakoLogCBox.SelectedIndexChanged += new EventHandler(kakoLogCBox_MouseClick);*/

            this.pinPointJPDate = "";
            //pinPointDateButtonParts.Text = "日時指定";

            //表示を解除
            try
            {
                fillBitmap.Dispose();
                pointBitmap.Dispose();
                synthesisBitmap.Dispose();
            }
            catch (System.Exception ex)
            {
                //Const.debugForm.OutPutDebug("Map", ex);
            }

            this.fillBitmap = (Bitmap)eternalFillBitmap.Clone();//ImageUtil.DeepCopy(eternalFillBitmap);
            this.pointBitmap = (Bitmap)eternalPointBitmap.Clone();//ImageUtil.DeepCopy(eternalPointBitmap);
            this.synthesisBitmap = ImageUtil.SynthesisImage(fillBitmap, pointBitmap);
            this.picBoxParts.Image = synthesisBitmap;

            //パワーを消す
            foreach (KeyValuePair<string, KokkaData> kvp in BasicMapData.japanNameDic)
            {
                kvp.Value.power = 0;
            }
            foreach (KeyValuePair<string, KokkaData> kvp in BasicMapData.kokkaNameDic)
            {
                kvp.Value.power = 0;
            }
            ClearIndexView();
        }

        private void ClearIndexView()
        {
            //Indexを再描画する
            foreach (stringstring temp in BasicMapData.kokkaList)
            {
                int num = temp.data1.IndexOf('(');
                if (num > 0)
                    temp.data1 = temp.data1.Substring(0, num);
            }
            foreach (stringstring temp in BasicMapData.kenList)
            {
                int num = temp.data1.IndexOf('(');
                if (num > 0)
                    temp.data1 = temp.data1.Substring(0, num);
            }
            Const.form.mainForm.BeginInvoke(
                new WriteBoardList_Delegate(
                    MapMainFormConst.countryIndexTabMain.countryIndexView.countryIndexControls.treeViewParts.WriteScreeningCountryBoardList),
                    MapMainFormConst.countryIndexTabMain.countryIndexView.countryIndexControls.treeViewParts, BasicMapData.kokkaList);

            Const.form.mainForm.BeginInvoke(
                 new WriteBoardList_Delegate(
                     MapMainFormConst.countryIndexTabMain.japanIndexView.countryIndexControls.treeViewParts.WriteScreeningCountryBoardList),
                     MapMainFormConst.countryIndexTabMain.japanIndexView.countryIndexControls.treeViewParts, BasicMapData.kenList);
            Const.form.mainForm.ReSetWaitCursor();
        }

        delegate void WriteBoardList_Delegate(TreeViewParts treeView, List<stringstring> strstrList);

        private void surviveImageButton_MouseClick(object sender, EventArgs e)
        {
            SurviveImage();
        }
        private void SurviveImage()
        {
            try
            {
                fileName = "subject_info";
                GetScreeningImage getScreeningImage = new GetScreeningImage(frontFile, fileName, nameDic, colorDic);
                BitmapSets bitmapSets = getScreeningImage.GetSurviveThreadImage();

                if (bitmapSets != null)
                {
                    fillBitmap.Dispose();
                    pointBitmap.Dispose();
                    fillBitmap = bitmapSets.fillBitmap;
                    pointBitmap = bitmapSets.pointBitmap;

                    synthesisBitmap = ImageUtil.SynthesisImage(fillBitmap, pointBitmap);
                    this.picBoxParts.Image.Dispose();
                    this.picBoxParts.Image = synthesisBitmap;
                }
            }
            catch { ;}

            GetScreeningIndex getScreeningIndex = new GetScreeningIndex(frontFile, fileName, nameDic, colorDic);
            getScreeningIndex.GetSurviveThreadIndex();
        }
        private void resetButton_MouseClick(object sender, EventArgs e)
        {
            try
            {
                fillBitmap.Dispose();
                pointBitmap.Dispose();
                synthesisBitmap.Dispose();
            }
            catch (System.Exception ex)
            {
                //Const.debugForm.OutPutDebug("Map", ex);
            }
            this.fillBitmap = (Bitmap)eternalFillBitmap.Clone();//ImageUtil.DeepCopy(eternalFillBitmap);
            this.pointBitmap = (Bitmap)eternalPointBitmap.Clone();//ImageUtil.DeepCopy(eternalPointBitmap);
            this.synthesisBitmap = ImageUtil.SynthesisImage(fillBitmap, pointBitmap);
            this.picBoxParts.Image = synthesisBitmap;

            //パワーを消す
            foreach (KeyValuePair<string, KokkaData> kvp in BasicMapData.japanNameDic)
            {
                kvp.Value.power = 0;
            }
            foreach (KeyValuePair<string, KokkaData> kvp in BasicMapData.kokkaNameDic)
            {
                kvp.Value.power = 0;
            }
            //Indexを再描画する
            ClearIndexView();
        }

        private void picBox_MouseClick(object sender, MouseEventArgs e)
        {
            Color color = backBitmap.GetPixel(e.X, e.Y);

            try
            {
                KokkaData kokkaData = colorDic[color.R.ToString() + "," + color.G.ToString() + "," + color.B.ToString()];

                if (e.Button == MouseButtons.Left)
                {
                    MainFormConst.boardListTabMain.show_board("local://screening/" + kokkaData.yomi, true);
                }
                else if (e.Button == MouseButtons.Right)
                {
                    ContextMenuControls.mapControlViewMenu.mapControlViewMenuEvent.Show(kokkaData.yomi, this.picBoxParts, new Point(e.X, e.Y));
                }

                return;
            }
            catch (System.Exception ex)
            {
                //Const.debugForm.OutPutDebug("Map", ex);
            }
        }
        private void FirstTimeJob()
        {
            if ((analysisDataDownload == false) && (FileIO.CheckIsFolder(Const.DataDir + Path.DirectorySeparatorChar + ".ageon" +
                Path.DirectorySeparatorChar + "cache" + Path.DirectorySeparatorChar + "screening") == false))
            {
                DialogResult result = MessageBox.Show("解析用のデータを受信しますか？",
                    "解析データがありません",
                    MessageBoxButtons.OKCancel,
                    MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button2);
  
                if (result == DialogResult.OK)
                {
                    MapMainFormConst.getScreeningData.StartScreening();
                    SurviveImage();
                }
                DialogResult result2 = MessageBox.Show("リロードボタンにより更新が可能です",
                    "お知らせ",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Asterisk,
                    MessageBoxDefaultButton.Button2);
            }
        }

        private void picBox_Kokka_MouseMove(object sender, MouseEventArgs e)
        {

            try
            {
                //初回だけ実行される
                FirstTimeJob();
                
                analysisDataDownload = true;

                PictureBox picTemp = (PictureBox)sender;
                
                Color color = backBitmap.GetPixel(e.X, e.Y);
                
                string key = color.R.ToString() + "," + color.G.ToString() + "," + color.B.ToString();

                if (colorDic.ContainsKey(key) == false)
                    return;

                KokkaData kokkaData = colorDic[color.R.ToString() + "," + color.G.ToString() + "," + color.B.ToString()];

                if (beforeKokkaData != null)
                    if (kokkaData.yomi.Equals(beforeKokkaData.yomi) == true)
                        return;

                //----国名・県名をツールチップで表示,件数も表示
                KokkaData kokkaDataPower = new KokkaData("", "", "", new Point(0, 0)); ;
                if (BasicMapData.japanNameDic.ContainsKey(kokkaData.yomi) == true)
                    kokkaDataPower = BasicMapData.japanNameDic[kokkaData.yomi];
                else if (BasicMapData.kokkaNameDic.ContainsKey(kokkaData.yomi) == true)
                    kokkaDataPower = BasicMapData.kokkaNameDic[kokkaData.yomi];
                else
                    kokkaDataPower.power = 0;
                string text = string.Format("{0}({1})", kokkaData.kanji, kokkaDataPower.power);
                toolTipParts.ShowToolTip2(text, this.picBoxParts);
                //----

                this.beforeKokkaData = kokkaData;

                Const.mapForm.toolStripTextBoxParts.Text = "local://screening/" + kokkaData.yomi;
                //MapMainFormConst.mapInfoMain.labelInfoParts.Text = string.Format("[{0}]", kokkaData.kanji);
                //MapMainFormConst.mapInfoMain.textInfomationParts.Text = string.Format("英語表記:[{0}]\r\n座標:[{1}-{2}]\r\n", kokkaData.yomi, e.X, e.Y);

                DrawFill(kokkaData.yomi);
                return;
            }
            catch (System.Exception ex)
            {
                /*Const.debugForm.OutPutDebug("Map", ex);

                if (beforeKokkaData != null)
                {
                    this.synthesisBitmap = ImageUtil.SynthesisImage(fillBitmap, pointBitmap);
                    this.picBoxParts.Image.Dispose();
                    this.picBoxParts.Image = this.synthesisBitmap;
                }
                beforeKokkaData = null;*/
            }
        }

        public void DrawFill(string yomi)
        {
            //sw.Reset();
            //sw.Start();

            List<Point> yokoPoint = new List<Point>();
            List<Point> tatePoint = new List<Point>();
            List<Point> addMapMarkPoint = new List<Point>();

            Point point;

            Bitmap pointBitmapTemp = (Bitmap)pointBitmap.Clone();//ImageUtil.DeepCopy(pointBitmap);
            //sw.Stop();
            
            //マークする点の座標を得る
            KokkaData kokkaData = nameDic[yomi];

            if (kokkaData.type.Equals("Mark") == true)
            {
                point = new Point(kokkaData.point.X, kokkaData.point.Y);
                addMapMarkPoint.Add(point);
            }
            else
            {
                point = new Point(kokkaData.point.X, kokkaData.point.Y);
            }

            //国ごとの場所データを加える
            if (kokkaData.type.Equals("Mark") == true)
            {
                SpecialPointWorld.AddMarkPoint(addMapMarkPoint, yomi);
            }
            else
            {
                SpecialPointWorld.AddMarkPoint(addMapMarkPoint, yomi);
                //塗りつぶす起点を得る
                SpecialPointWorld.AddPoint(yokoPoint, yomi, ref point, fillBitmap.Width, fillBitmap.Height);
            }

            pointBitmapTemp = DrawMarkPoint(pointBitmapTemp, addMapMarkPoint, 0, 0, 255);

            //初期化
            addMapMarkPoint.Clear();
            //addMapMarkPoint = null;

            Bitmap fillBitmapTemp = DrawCruciformPoint(fillBitmap, yokoPoint, 0, 0, 255);
            yokoPoint.Clear();

            synthesisBitmap = ImageUtil.SynthesisImage(fillBitmapTemp, pointBitmapTemp);
            //synthesisBitmap = ImageUtil.SynthesisImageUnsafe(fillBitmapTemp, pointBitmapTemp);


            pointBitmapTemp.Dispose();
            fillBitmapTemp.Dispose();
            //表示する
            picBoxParts.Image.Dispose();
            picBoxParts.Image = synthesisBitmap;
            //sw.Stop();
            //Const.mapForm.mapMainForm.Text = sw.ElapsedMilliseconds.ToString();
        }
    }
}