using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;

namespace HistoryDLL
{
    public partial class CyclicScroller : UserControl,IDisposable
    {
        private int AutoRunVelocityValue = 0;

        private bool IsConfigSettingExist = false;

        private List<bool> canUsingLangList = new List<bool>(4) { false, false, false, false };

        /// <summary>
        /// 初始化除了Spec外的基本設定
        /// </summary>
        private void InitialWholeSetting(string settingPath = null)
        {
            //建Setting Folder 並判斷是否有存在 ConfigSetting.ini 檔案
            if (!Directory.Exists(GlobalFunction.settingPath))
            {
                Directory.CreateDirectory(GlobalFunction.settingPath);
            }
            else if (File.Exists(GlobalFunction.ConfigSettingFilePath))
            {
                IsConfigSettingExist = true;
            }

            //設定是否啟用切換主標題語系功能
            SetChangeLangStatus();
            //設定是否啟用回首頁功能
            SetHomeBtnStatus();
            //取得自動輪播時候的速度
            AutoRunVelocityValue = GetAutoRunVelocity();
            //掛載 StoryBoard 完成後的事件
            storyboardForLocate.Completed += new EventHandler(storyboardForLocate_Completed);
            //設定自動輪撥的 Timer
            GlobalFunction.CheckAutoRunTimer.Interval = TimeSpan.FromMilliseconds(ConfigSettingClass.MainBackCollect.BackHomeMillisecond * 1000);
            GlobalFunction.CheckAutoRunTimer.Tick += CheckAutoRunTimer_Tick;
            // 取得 4K 解析度設定
            GlobalFunction.isSolutionUsing4K = ConfigSettingClass.MainBackCollect.IsUsing4kResolution;

            //設定背景圖
            if (IsConfigSettingExist)
            {
                if (File.Exists(GlobalFunction.thumbPath + ConfigSettingClass.MainBackCollect.ImgBackground))
                {
                    this.uxBackGroundImg.Visibility = System.Windows.Visibility.Visible;
                    this.Background = Brushes.White;
                    this.uxBackGroundImg.Source = GetBitMap(GlobalFunction.thumbPath + ConfigSettingClass.MainBackCollect.ImgBackground);
                }
                else
                {
                    this.uxBackGroundImg.Visibility = System.Windows.Visibility.Collapsed;
                    this.Background = new SolidColorBrush(ConfigSettingClass.MainBackCollect.BackgroundColor);
                }
            }
            else
            {
                //如無設定檔案~則依照解析度載入對應的圖檔
                LoadBackgroundFromResolution();
            }
            //設定左上及右上logo
            if (File.Exists(GlobalFunction.thumbPath + ConfigSettingClass.MainBackCollect.ImgLogo))
            {
                uxLeftLogoMap.Visibility = Visibility.Visible;
                uxRightLogoMap.Visibility = Visibility.Visible;

                uxLeftLogoMap.Source = new BitmapImage(new Uri(GlobalFunction.thumbPath + ConfigSettingClass.MainBackCollect.ImgLogo));
                uxRightLogoMap.Source = new BitmapImage(new Uri(GlobalFunction.thumbPath + ConfigSettingClass.MainBackCollect.ImgLogo));

                RenderOptions.SetBitmapScalingMode(uxLeftLogoMap, BitmapScalingMode.HighQuality);
                RenderOptions.SetBitmapScalingMode(uxRightLogoMap, BitmapScalingMode.HighQuality);
            }
            else
            {
                uxLeftLogoMap.Opacity = 0;
                uxRightLogoMap.Opacity = 0;
            }
        }

        private void LoadBackgroundFromResolution()
        {
            if (CurrentMonitorCount.ncm == MonitorFlag.Monitor1_1)
            {
                //this.Background = new ImageBrush(new BitmapImage(new Uri(GlobalFunction.thumbPath + "1x1.jpg")));
            }
            else if (CurrentMonitorCount.ncm == MonitorFlag.Monitor2_1)
            {
                this.Background = new ImageBrush(new BitmapImage(new Uri(GlobalFunction.thumbPath + "1x2.jpg")));
            }
            else if (CurrentMonitorCount.ncm == MonitorFlag.Monitor3_1)
            {
                this.Background = new ImageBrush(new BitmapImage(new Uri(GlobalFunction.thumbPath + "1x3.jpg")));
            }
        }

        //透過ChangeLan.txt 取得是否顯示改變主標題語系功能
        private void SetChangeLangStatus()
        {
            if (File.Exists(GlobalFunction.CanChangeLangPath))
            {
                string text = System.IO.File.ReadAllText(GlobalFunction.CanChangeLangPath);
                int usingCount = 0;

                if (text.ToLower() == "true")
                {
                    if (ConfigSettingClass.MainBackCollect.LangText[0] != "")
                    {
                        canUsingLangList[0] = true;
                        usingCount++;
                    }

                    if (ConfigSettingClass.MainBackCollect.LangText[1] != "")
                    {
                        canUsingLangList[1] = true;
                        usingCount++;
                    }

                    if (ConfigSettingClass.MainBackCollect.LangText[2] != "")
                    {
                        canUsingLangList[2] = true;
                        usingCount++;
                    }

                    if (ConfigSettingClass.MainBackCollect.LangText[3] != "")
                    {
                        canUsingLangList[3] = true;
                        usingCount++;
                    }
                }

                if (usingCount >= 2)
                {
                    uxMainLangBtnR.Visibility = Visibility.Visible;
                    uxMainLangBtnL.Visibility = Visibility.Visible;
                }
            }
        }

        //透過HomeClick.txt 取得是否顯示回首頁功能
        private void SetHomeBtnStatus()
        {
            if (File.Exists(GlobalFunction.CanHomeClickPath))
            {
                string text = System.IO.File.ReadAllText(GlobalFunction.CanHomeClickPath);

                if (text.ToLower() == "true")
                {
                    uxHomeBtnR.Visibility = Visibility.Visible;
                    uxHomeBtnL.Visibility = Visibility.Visible;
                }
            }
        }

        //透過Velocity.txt 取得設定的自動輪播速度
        private int GetAutoRunVelocity()
        {
            int result = 5;

            if (File.Exists(GlobalFunction.AutoRunVelocityPath))
            {
                string text = System.IO.File.ReadAllText(GlobalFunction.AutoRunVelocityPath);

                result = int.Parse(text);
            }

            return result;
        }

        //設定自動輪播的動畫
        private void SetAutoRunStoryBoard(double from, double to)
        {
            autoRunStoryboard.Children.Clear();

            DoubleAnimation dbOffset = new DoubleAnimation()
            {
                Duration = TimeSpan.FromSeconds(AutoRunVelocityValue),
            };

            ScrollViewerUtilities.UseMotionStop = false;
            Storyboard.SetTarget(dbOffset, (DependencyObject)this.FindName("uxMyScroll"));
            Storyboard.SetTargetProperty(dbOffset, new PropertyPath(ScrollViewerUtilities.HorizontalOffsetProperty));
            autoRunStoryboard.Children.Add(dbOffset);
            autoRunStoryboard.FillBehavior = FillBehavior.HoldEnd;

            dbOffset.From = from;
            dbOffset.To = to;
        }

        private ImageSource GetBitMap(string imgpath)
        {
            BitmapImage bitmapImg = new BitmapImage();

            bitmapImg.BeginInit();
            bitmapImg.UriSource = new Uri(imgpath, UriKind.RelativeOrAbsolute);
            //忽略原始圖檔的色盤設定，使用預設值，可縮短載入圖檔的時間
            //如有遇到色彩不正確的問題，或者原圖有特殊的自定義色盤，請不要使用此設定
            bitmapImg.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
            //使用以下的預先載入設定，在BitmapImage創建完成之後，可立刻釋放其所占用或鎖住的資源，以免咬住檔案
            bitmapImg.CacheOption = BitmapCacheOption.OnLoad;
            //根據欲顯示的區域長或寬，來設定 DecodePixelHeight 或 DecodePixelWidth 的值
            bitmapImg.EndInit();
            bitmapImg.Freeze();

            return bitmapImg;
        }

        /// <summary>
        /// 新建出 Grid For 裝載DetailViewer
        /// </summary>
        private void CreateExtraUnitGrid()
        {
            ExtraUnitGridList.Clear();

            for (int count = 0; count < ChildrenCount; count++)
            {
                ExtraUnitGrid ExtraGrid = new ExtraUnitGrid(MainEventWidth, MainEventHeight, YearEventHeight, NoneUseRange);

                ExtraGrid.ExtraUnitGridBubbleToCyclicScrollerEvent += new ExtraUnitGrid.ExtraUnitGridBubbleToCyclicScroller(ExtraGrid_ExtraUnitGridBubbleToCyclicScrollerEvent);
                ExtraUnitGridList.Add(ExtraGrid);
            }
        }

        /// <summary>
        /// 初始化該 ExtraUnitGrid ~包括 狀態 位置 
        /// </summary>
        private void InitializeExtraUnitGrid()
        {
            int index = 1;
            //替每個 Grid 標上索引值~該索引值是代表該Grid在螢幕上的位置(從1開始算起)
            //且如果是第一個或者是最後一個~則狀態UnUse灰色
            for (int count = 0; count < ExtraUnitGridList.Count; count++)
            {
                ExtraUnitGridList[count].Get_Set_MonitorIndex = index;

                //設定狀態
                if (index == 1 || index == ExtraUnitGridList.Count)
                {
                    //判斷用
                    ExtraUnitGridList[count].Get_Set_BlockControlMode = ExtraUnitGrid.ControlMode.UnUse;
                    //回原始狀態用
                    ExtraUnitGridList[count].SetOriControlMode(ExtraUnitGrid.ControlMode.UnUse);
                }
                else
                {
                    ExtraUnitGridList[count].Get_Set_BlockControlMode = ExtraUnitGrid.ControlMode.CanExtend;
                    ExtraUnitGridList[count].SetOriControlMode(ExtraUnitGrid.ControlMode.CanExtend);
                }
                index++;
            }
            //調整位置
            for (int count = 0; count < ExtraUnitGridList.Count; count++)
            {
                //先設定第一個
                if (count == 0)
                {
                    ExtraUnitGridList[count].Margin = new Thickness(-NoneUseRange, 0, 0, uxMyScroll.Margin.Bottom - 5);
                    ExtraUnitGridList[count].RecodeMarginLeft = ExtraUnitGridList[count].Margin.Left;
                    continue;
                }
                ExtraUnitGridList[count].Margin = new Thickness(ExtraUnitGridList[count - 1].Margin.Left + MainEventWidth, 0, 0, uxMyScroll.Margin.Bottom - 5);
                ExtraUnitGridList[count].RecodeMarginLeft = ExtraUnitGridList[count].Margin.Left;
            }
        }

        /// <summary>
        /// 設定當前語系
        /// </summary>
        private void SetLanguage()
        {
            //預設
            System.Windows.Application.Current.Properties["Language"] = "Language1";
            uxMainLangBtnL.Content = ConfigSettingClass.MainBackCollect.LangText[0];
            uxMainLangBtnR.Content = ConfigSettingClass.MainBackCollect.LangText[0];
            //如果更改
            if (ConfigSettingClass.MainBackCollect.DefaultLangIndex == 1)
            {
                System.Windows.Application.Current.Properties["Language"] = "Language2";
                uxMainLangBtnL.Content = ConfigSettingClass.MainBackCollect.LangText[1];
                uxMainLangBtnR.Content = ConfigSettingClass.MainBackCollect.LangText[1];
            }
            else if (ConfigSettingClass.MainBackCollect.DefaultLangIndex == 2)
            {
                System.Windows.Application.Current.Properties["Language"] = "Language3";
                uxMainLangBtnL.Content = ConfigSettingClass.MainBackCollect.LangText[2];
                uxMainLangBtnR.Content = ConfigSettingClass.MainBackCollect.LangText[2];
            }
            else if (ConfigSettingClass.MainBackCollect.DefaultLangIndex == 3)
            {
                System.Windows.Application.Current.Properties["Language"] = "Language4";
                uxMainLangBtnL.Content = ConfigSettingClass.MainBackCollect.LangText[3];
                uxMainLangBtnR.Content = ConfigSettingClass.MainBackCollect.LangText[3];
            }
        }

        /// <summary>
        /// 設定回正被中斷時~應該回到的顯示位置
        /// </summary>
        private void SetReturnPos()
        {
            System.Windows.Application.Current.Properties["ReturnPos"] = MainEventWidth + NoneUseRange;
        }

        /// <summary>
        /// 判斷當前的Index是否超出"最大"容許範圍~進行調整
        /// </summary>
        /// <returns></returns>
        private int GetIndexFromRightSide()
        {
            int index = currentLoadIndex;

            if (index < LiveContainerList.Count)
            {
                index += 1;
            }
            else
            {
                index = 1;
            }

            return index;
        }

        /// <summary>
        /// 判斷當前的Index是否低於"最小"容許範圍~進行調整
        /// </summary>
        /// <returns></returns>
        private int GetIndexFromLeftSide()
        {
            int index = currentLoadIndex;

            if (index > 0)
            {
                index -= 1;
            }
            else
            {
                index = LiveContainerList.Count - 1;
            }

            return index;
        }

        /// <summary>
        /// 透過螢幕可容納的個數取得當前年份中間位置
        /// </summary>
        /// <returns></returns>
        private int GetCenterIndexValue()
        {
            int result = 0;

            switch (CurrentMonitorCount.ncm)
            {
                case MonitorFlag.Monitor1_1:
                case MonitorFlag.Monitor2_1:
                case MonitorFlag.Monitor3_1:
                case MonitorFlag.Monitor4_1:
                case MonitorFlag.Monitor5_1:
                case MonitorFlag.Monitor6_1:
                    {
                        result = ChildrenCount / 2;
                        break;
                    }
            }

            return result;
        }

        #region 首頁動畫
        /// <summary>
        /// 計算總事件~並將該直傳到Homepage中
        /// </summary>
        private void CalcCountToHomePage()
        {
            if (!RunHomePageAnimation)
            {
                return;
            }
            int staticvalue = GetCycleCount();
            int totalevent = 0;

            for (int index = 0; index < staticvalue; index++)
            {
                for (int count = 0; count < xmlDataList.Count; count++)
                {
                    totalevent += xmlDataList[count].monthclassList.Count;
                }
            }
            hp.SetEventCount(totalevent);
        }

        /// <summary>
        /// Loading start
        /// </summary>
        private void LoadingStart()
        {
            if (RunHomePageAnimation)
            {
                this.uxCyclicGrid.Opacity = 0;
            }
        }

        private void AddHomePageAnimation()
        {
            if (RunHomePageAnimation)
            {
                hp = new HomePage(ResolutionValueWidth, ResolutionValueHeight);
                hp.SetBlockCommonSetting(MainEventWidth, YearEventHeight, NoneUseRange);
                hp.SetHistoryWallControl(uxCyclicGrid);
                hp.OnLoadProgessComplete += Hp_OnLoadProgessComplete;
                uxMainWindow.Children.Add(hp);
            }
        }

        private void Hp_OnLoadProgessComplete(object sender, EventArgs e)
        {
            OnDataLoadCompeleted?.Invoke(this,null);
        }
        #endregion

        #region 自動輪播相關
        void CheckAutoRunTimer_Tick(object sender, EventArgs e)
        {
            // 確認 Detailviewer 狀況 sdlu
            if (CheckExtraGridIsVideoRun())
            {
                //將上層Grid關閉
                CloseExtraGrid();
                //自動輪播開始
                WpfDelayDoWork.DoWork(HistoryWallAutoRun, 1000);
                isAutoRun = true;
                GlobalFunction.CheckAutoRunTimer.Stop();
            }
        }

        private bool CheckExtraGridIsVideoRun()
        {
            bool isCheckVideo = true;

            int count = ExtraUnitGridList.Count;

            for (int i = 0; i < count; i++)
            {
                Grid gd = ExtraUnitGridList[i].BorderUp.Child as Grid;

                if (gd != null && gd.Children.Count > 0)
                {
                    DetailViewer dv = gd.Children[0] as DetailViewer;

                    if (dv.isPlayVideo)
                    {
                        isCheckVideo = false;
                        break;
                    }
                }
            }

            return isCheckVideo;
        }

        /// <summary>
        /// 關閉上層Grid
        /// </summary>
        private void CloseExtraGrid()
        {
            int count = ExtraUnitGridList.Count;

            for (int i = 0; i < count; i++)
            {
                ExtraUnitGridList[i].BorderDown_TouchUp(null, null);
            }
        }

        /// <summary>
        /// 自動移動啟動
        /// </summary>
        private void HistoryWallAutoRun()
        {
            if (ControlMode == HistoryControlMode.Manual)
            {
                ControlMode = HistoryControlMode.AutoRun;
                SendControlModeToLiveContainer(ControlMode);
                SetAutoRunStoryBoard(this.uxMyScroll.HorizontalOffset, this.uxMyScroll.HorizontalOffset + MainEventWidth);
                autoRunStoryboard.Begin();
            }
        }

        /// <summary>
        /// 關閉自動移動
        /// </summary>
        private void StopAutoRunTheWall()
        {
            if (ControlMode == HistoryControlMode.AutoRun)
            {
                ScrollViewerUtilities.UseMotionStop = true;
                autoRunStoryboard.Stop();
                ControlMode = HistoryControlMode.Manual;
                SendControlModeToLiveContainer(ControlMode);
            }
        }
        #endregion

        public void Dispose()
        {
            GlobalFunction.CheckAutoRunTimer.Tick -= CheckAutoRunTimer_Tick;
        }
    }
}
