using FirstFloor.ModernUI.Windows.Controls;
using Newtonsoft.Json;
using HistoryWallEditTool.Controls;
using HistoryWallEditTool.ControlsForData;
using HistoryWallEditTool.Helper;
using HistoryWallEditTool.JsonFile;
using HistoryWallEditTool.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Threading;

namespace HistoryWallEditTool
{
    /// <summary>
    /// MainWindow.xaml 的互動邏輯
    /// </summary>
    public partial class HistoryWall : UserControl
    {
        #region Static Members
        public static HistoryWall WINDOW;
        public static int screenWidth, screenHeight, dialogPositionDiff;
        public static string LangString = "zh-TW";

        public static MainBackground MainBackCollect = new MainBackground()
        {
            BackgroundColor = Color.FromArgb(255, 255, 255, 255),
            BackgroundColorPoint = new Point(0, 0),
            ImgBackground = String.Empty,
            ImgLogo = String.Empty,
            DefaultLangIndex = 0,
            BackHomeMillisecond = 20,
            ScreenSetting = 1,
            LangText = new string[] { "中文", "", "", "" },
            LangFlowDir = new FlowDirection[] { FlowDirection.LeftToRight, FlowDirection.LeftToRight, FlowDirection.LeftToRight, FlowDirection.LeftToRight },
            IsUsing4kResolution = false
        };

        public static Event EventCollect = new Event()
        {
            BackgroundColor = Color.FromArgb(230, 3, 115, 185),
            BackgroundColorPoint = new Point(0, 0),
            TextColor = Color.FromArgb(255, 232, 238, 255),
            TextColorPoint = new Point(0, 0),
            ThicknessColor = Color.FromArgb(255, 177, 232, 255),
            ThicknessColorPoint = new Point(0, 0)
        };
        public static EventContent EventContentCollect = new EventContent()
        {
            BackgroundColor = Color.FromArgb(233, 115, 217, 255),
            BackgroundColorPoint = new Point(0, 0),
            TextColor = Color.FromArgb(198, 0, 6, 9),
            TextColorPoint = new Point(0, 0),
            ThicknessColor = Color.FromArgb(255, 198, 255, 255),
            ThicknessColorPoint = new Point(0, 0)
        };
        public static Timeline TimelineCollect = new Timeline()
        {
            BackgroundColor = Color.FromArgb(177, 168, 197, 255),
            BackgroundColorPoint = new Point(0, 0),
            TextColor = Color.FromArgb(176, 255, 255, 255),
            TextColorPoint = new Point(0, 0),
            ThicknessColor = Color.FromArgb(255, 0, 87, 154),
            ThicknessColorPoint = new Point(0, 0)
        };
        public static TimelineExtent TimelineExtentCollect = new TimelineExtent()
        {
            BackgroundColor = Color.FromArgb(204, 0, 41, 104),
            BackgroundColorPoint = new Point(0, 0),
            TextColor = Color.FromArgb(255, 162, 220, 255),
            TextColorPoint = new Point(0, 0),
            ThicknessColor = Color.FromArgb(255, 76, 49, 0),
            ThicknessColorPoint = new Point(0, 0)
        };
        public static ButtonSelect BtnSelectCollect = new ButtonSelect()
        {
            BackgroundColor = Color.FromArgb(168, 12, 0, 0),
            BackgroundColorPoint = new Point(0, 0),
            TextColor = Color.FromArgb(255, 222, 241, 255),
            TextColorPoint = new Point(0, 0),
            BackgroundColorUnselect = Color.FromArgb(168, 0, 129, 181),
            BackgroundColorUnselectPoint = new Point(0, 0),
            TextColorUnselect = Color.FromArgb(120, 255, 255, 255),
            TextColorUnselectPoint = new Point(0, 0)
        };
        #endregion

        //初始化 GlobalFunction
        private GlobalFunction globalfunction = new GlobalFunction();
        HistoryWallEventJson hweventJson = new HistoryWallEventJson();

        //page 2 controller
        MainContainer mc;
        //預設是時間軸的顯示方式
        public ControlLine curControlLine = ControlLine.Time;

        private void LoadConfig()
        {
            if (File.Exists(GlobalFunction.ConfigFilePath))
            {
                string jsonResult;
                using (StreamReader sr = new StreamReader(GlobalFunction.ConfigFilePath))
                {
                    jsonResult = sr.ReadToEnd();
                }
                var container = UtilityFunctions.DeserializeFromJson<DataCollect>(jsonResult);
                MainBackCollect = container.MainBackgroundCollect;
                EventCollect = container.EventCollect;
                EventContentCollect = container.EventContentCollect;
                TimelineCollect = container.TimelineCollect;
                TimelineExtentCollect = container.TimelineExtentCollect;
                BtnSelectCollect = container.ButtonSelectCollect;
            }
            else
            {
                SetDefaultBgAndLogo();
            }
        }

        private void DetectCorrectConfig()
        {
            CtrlDataUpgradeMap(Visibility.Visible);
            #region config
            MainBackCollect.ImgBackground = Path.GetFileName(MainBackCollect.ImgBackground);
            MainBackCollect.ImgLogo = Path.GetFileName(MainBackCollect.ImgLogo);
            string[] newLangText = new string[4];

            for (int i = 0; i < newLangText.Length; i++)
            {
                if (MainBackCollect.LangText != null && i < MainBackCollect.LangText.Length)
                    newLangText[i] = MainBackCollect.LangText[i];
                else
                    newLangText[i] = "";
            }
            MainBackCollect.LangText = newLangText;
            FlowDirection[] newLangFlowDir = new FlowDirection[4];

            for (int i = 0; i < newLangFlowDir.Length; i++)
            {
                if (MainBackCollect.LangFlowDir != null && i < MainBackCollect.LangFlowDir.Length)
                    newLangFlowDir[i] = MainBackCollect.LangFlowDir[i];
                else
                    newLangFlowDir[i] = FlowDirection.LeftToRight;
            }
            MainBackCollect.LangFlowDir = newLangFlowDir;
            #endregion

            #region data
            if (hweventJson != null)
            {
                for (int i = 0; i < hweventJson.EventGroups.Count; i++)
                {
                    if (hweventJson.EventGroups[i].Year != null && hweventJson.EventGroups[i].Year != "")
                    {
                        hweventJson.EventGroups[i].YearLan1 = hweventJson.EventGroups[i].Year;
                    }

                    for (int j = 0; j < hweventJson.EventGroups[i].ListDates.Count; j++)
                    {
                        if (hweventJson.EventGroups[i].ListDates[j].Month == null)
                            hweventJson.EventGroups[i].ListDates[j].Month = "";
                        if (hweventJson.EventGroups[i].ListDates[j].Script1 == null)
                            hweventJson.EventGroups[i].ListDates[j].Script1 = "";
                        if (hweventJson.EventGroups[i].ListDates[j].Script2 == null)
                            hweventJson.EventGroups[i].ListDates[j].Script2 = "";
                        if (hweventJson.EventGroups[i].ListDates[j].TitleLan1 == null)
                            hweventJson.EventGroups[i].ListDates[j].TitleLan1 = "";
                        if (hweventJson.EventGroups[i].ListDates[j].TitleLan2 == null)
                            hweventJson.EventGroups[i].ListDates[j].TitleLan2 = "";
                    }
                }
            }
            #endregion
            CtrlDataUpgradeMap(Visibility.Collapsed);
        }

        private void CtrlDataUpgradeMap(Visibility visibility)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
            {
                uxDataUpdateGd.Visibility = visibility;
            });
        }

        private void SetDefaultBgAndLogo()
        {
            int Width = (int)SystemParameters.PrimaryScreenWidth;
            int screenCount = Width / 1920;
            if (screenCount == 1)
            {
                MainBackCollect.ImgBackground = "1x1.jpg";
                MainBackCollect.ScreenSetting = 1;
            }
            else if (screenCount == 2)
            {
                MainBackCollect.ImgBackground = "1x2.jpg";
                MainBackCollect.ScreenSetting = 2;
            }
            else if (screenCount == 3)
            {
                MainBackCollect.ImgBackground = "1x3.jpg";
                MainBackCollect.ScreenSetting = 3;
            }
            MainBackCollect.ImgLogo = "logo.png";
        }

        public HistoryWall()
        {
            InitializeComponent();

            screenHeight = (int)SystemParameters.PrimaryScreenHeight;
            screenWidth = (int)SystemParameters.PrimaryScreenWidth;
            dialogPositionDiff = (screenWidth - 1920) / 2;
            WINDOW = this;
            //避免沒有資料夾造成的錯誤~先檢查資料夾是否存在
            CreateDataFolder();

            //載入歷史事件
            LoadHistoryEvent();
            //載入外觀設定
            LoadConfig();
            // 檢查是否有遺失的設定
            DetectCorrectConfig();

            // 取得是否為 4K 設定
            GetConfigFor4K();

            //整理圖片資料夾~避免有些資料夾沒用到卻存在
            ReformingImgFolder();
            //透過歷史資料初始化 historyWall 的編輯頁內容
            ReloadMainContainer();

            //this.Style = (Style)App.Current.Resources["MyEmptyWindow"];

            LoadDefaultConfig();
        }


        private void GetConfigFor4K()
        {
            if (File.Exists(GlobalFunction.UsingDisplayOn4KsPath))
            {
                string text = System.IO.File.ReadAllText(GlobalFunction.UsingDisplayOn4KsPath);

                if (text.ToLower() == "true")
                    GlobalFunction.isSolutionUsing4K = true;
                else
                    GlobalFunction.isSolutionUsing4K = false;
            }
        }

        private void CreateDataFolder()
        {
            if (!Directory.Exists(GlobalFunction.dataPath + @"\HistoryWallData"))
            {
                Directory.CreateDirectory(GlobalFunction.dataPath + @"\HistoryWallData");
            }
            if (!Directory.Exists(GlobalFunction.dataPath + @"\HistoryImage"))
            {
                Directory.CreateDirectory(GlobalFunction.dataPath + @"\HistoryImage");
            }
        }

        private void ReformingImgFolder()
        {
            List<string> useFolderPath = new List<string>();
            List<string> dirlist = new List<string>();

            foreach (string item in Directory.GetDirectories(MainContainer.imgFolderName))
            {
                dirlist.Add(Path.GetFileNameWithoutExtension(item));
            }

            for (int i = 0; i < hweventJson.EventGroups.Count; i++)
            {
                for (int j = 0; j < hweventJson.EventGroups[i].ListDates.Count; j++)
                {
                    useFolderPath.Add(hweventJson.EventGroups[i].ListDates[j].ImagePath);
                }
            }

            for (int index = 0; index < dirlist.Count; index++)
            {
                if (!useFolderPath.Contains(dirlist[index]))
                {
                    Directory.Delete(MainContainer.imgFolderName + dirlist[index], true);
                }
            }
        }

        private void ReloadMainContainer()
        {
            mc = new MainContainer(hweventJson);
        }

        public static T DeserializeFromJson<T>(string json)
        {
            T deserializedProduct = JsonConvert.DeserializeObject<T>(json);
            return deserializedProduct;
        }

        private void LoadHistoryEvent()
        {
            hweventJson = new HistoryWallEventJson();

            if (File.Exists(GlobalFunction.JsonFilePath))
            {
                string jsonResult;

                using (StreamReader sr = new StreamReader(GlobalFunction.JsonFilePath))
                {
                    jsonResult = sr.ReadToEnd();
                }
                hweventJson = DeserializeFromJson<HistoryWallEventJson>(jsonResult);
            }
        }

        private void LoadDefaultConfig()
        {
            //預設顯示頁面 - 外觀設定
            //uxDisplaySettingBtn.IsChecked = true;
            uxDataSettingBtn.IsChecked = true;
            //預設時間軸與分類軸顯示
            mc.SetCurControlLine(curControlLine);
            //預設語系 - 中文
            uxLangChi.IsChecked = true;
            //資料內容預設為第一個語系
            uxLangOne.IsChecked = true;
            uxLangOne.Content = MainBackCollect.LangText[0];
            uxLangTwo.Content = MainBackCollect.LangText[1];
            uxLangThree.Content = MainBackCollect.LangText[2];
            uxLangFour.Content = MainBackCollect.LangText[3];
        }
        /*
        #region windows close and miniScreen
        private void uxWinCloseBtn_Click(object sender, RoutedEventArgs e)
        {
            SaveConfig();
            mc.SaveCurDataToJson();
            SaveDataToJson();
            this.Close();
        }

        private void uxWinMiniBtn_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
        #endregion
        */

        private void CloseDetailDataViewerMedia()
        {
            if (mc.uxDetailGrid.Children.Count != 0)
            {
                DetailDataViewer ddvDetail = mc.uxDetailGrid.Children[0] as DetailDataViewer;

                //關閉影片並重新載入影片的縮圖
                ddvDetail.AutoCloseChildMediaPlay(-1);
            }
        }

        private void uxDisplaySettingBtn_Checked(object sender, RoutedEventArgs e)
        {
            //將歷史事件編輯工具中 DetailDataViewer 內如有影片播放~則關閉該影片
            CloseDetailDataViewerMedia();
            uxContainer.Children.Clear();
            uxContainer.Children.Add(new DisplaySettingControl());
        }

        private void uxDataSettingBtn_Checked(object sender, RoutedEventArgs e)
        {
            uxContainer.Children.Clear();
            uxContainer.Children.Add(mc);
        }

        private void SaveDataToJson()
        {
            string jsonString = JsonConvert.SerializeObject(hweventJson, Newtonsoft.Json.Formatting.Indented);
            using (StreamWriter sw = new StreamWriter(GlobalFunction.JsonFilePath, false, Encoding.Unicode))
            {
                sw.Write(jsonString);
                sw.Close();
            }
        }

        private void uxLaunchBtn_Checked(object sender, RoutedEventArgs e)
        {
            //外觀設定工具
            SaveConfig();
            //事件編輯工具
            mc.SaveCurDataToJson();
            SaveDataToJson();
            //啟動程式
            Exception closeExcept = CloseProcess("nLightenHistoryWall");
            Thread.Sleep(100);
            Exception ex = OpenMainProgram(GlobalFunction.rootPath + "nLightenHistoryWall.exe");

            if (ex != null)
            {
                MessageBox.Show(ex.Message);
            }
            else
            {
                //把自己關掉
                //this.Close();
            }
        }

        #region 發送信號~判斷子視窗是否要移除焦點
        private void uxMainWindow_MouseUp(object sender, MouseButtonEventArgs e)
        {
            mc.RemoveFocus();
        }

        private void uxMainWindow_MouseDown(object sender, MouseButtonEventArgs e)
        {
            mc.CheckFocus();
        }
        #endregion

        //切換時間軸顯示方式 (時間軸 or 分類軸)
        private void uxlineChk_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton rb = sender as RadioButton;

            if (rb.Tag.ToString() == "TimeLine")
            {
                curControlLine = ControlLine.Time;
            }
            else if (rb.Tag.ToString() == "ClassLine")
            {
                curControlLine = ControlLine.Class;
            }

            mc.SetCurControlLine(curControlLine);
        }

        //切換頁面上的字體語系
        private void SysLanChange_Checked(object sender, RoutedEventArgs e)
        {
            string resourcePrefix = "StringResources";
            string culturesFolder = "Culture";
            RadioButton rb = sender as RadioButton;

            if (rb != null)
            {
                this.Resources.MergedDictionaries.Clear();
                string loadedFileName = string.Format("{0}\\{1}\\{2}.{3}.xaml",
                   GlobalFunction.rootPath,
                   culturesFolder,
                   resourcePrefix,
                   rb.Tag.ToString());

                FileStream fileStream = new FileStream(loadedFileName, FileMode.Open);
                ResourceDictionary resourceDictionary = XamlReader.Load(fileStream) as ResourceDictionary;
                this.Resources.MergedDictionaries.Add(resourceDictionary);
                ChangeTaskDialogMsgLang(rb.Tag.ToString());
            }
        }

        private void ChangeTaskDialogMsgLang(string lang)
        {
            if (lang == "en-US")
            {
                TaskDialogMsg.cdl = CurrentDisplayLanguage.ENG;
                SelectDialogControl.cdl = CurrentDisplayLanguage.ENG;
                SelectLangControl.cdl = CurrentDisplayLanguage.ENG;
                SettingControlVertical.cdl = CurrentDisplayLanguage.ENG;
                SettingWindow.cdl = CurrentDisplayLanguage.ENG;
            }
            else
            {
                TaskDialogMsg.cdl = CurrentDisplayLanguage.CHT;
                SelectDialogControl.cdl = CurrentDisplayLanguage.CHT;
                SelectLangControl.cdl = CurrentDisplayLanguage.CHT;
                SettingControlVertical.cdl = CurrentDisplayLanguage.CHT;
                SettingWindow.cdl = CurrentDisplayLanguage.CHT;
            }
        }

        //切換現階段要編輯的歷史事件語系
        private void HisEventLanChange_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton rb = sender as RadioButton;

            if (rb != null)
            {
                if (rb.Tag.ToString() == "EventLangOne")
                {
                    mc.ChangeEventEditLan(CurrentEditLanguage.LanguageOne);
                }
                else if (rb.Tag.ToString() == "EventLangTwo")
                {
                    mc.ChangeEventEditLan(CurrentEditLanguage.LanguageTwo);
                }
                else if (rb.Tag.ToString() == "EventLangThree")
                {
                    mc.ChangeEventEditLan(CurrentEditLanguage.LanguageThree);
                }
                else if (rb.Tag.ToString() == "EventLangFour")
                {
                    mc.ChangeEventEditLan(CurrentEditLanguage.LanguageFour);
                }
            }
        }

        public void SaveConfig()
        {
            try
            {
                DataCollect collect = new DataCollect();
                collect.MainBackgroundCollect = MainBackCollect;
                collect.EventCollect = EventCollect;
                collect.EventContentCollect = EventContentCollect;
                collect.TimelineCollect = TimelineCollect;
                collect.TimelineExtentCollect = TimelineExtentCollect;
                collect.ButtonSelectCollect = BtnSelectCollect;
                string jsonString = JsonConvert.SerializeObject(collect, Newtonsoft.Json.Formatting.Indented);
                using (StreamWriter sw = new StreamWriter(GlobalFunction.ConfigFilePath, false, Encoding.Unicode))
                {
                    sw.Write(jsonString);
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, (string)FindResource("saveFailed"));
            }
        }

        public void EndSetting() { }

        #region Delegate

        public delegate void CallBackToUIThread(string state);

        #endregion

        public event CallBackToUIThread create_event;

        public void SaveWholeConfig()
        {
            SaveDataToJson();
            SaveConfig();
        }
    }
}
