using MediaViewerLib.Utilities;
using System;
using System.Collections.Generic;
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.Imaging;

namespace HistoryDLL
{
    /// <summary>
    /// CyclicScroller 事件傳遞與通訊
    /// </summary>
    public partial class CyclicScroller : UserControl
    {
        //外掛 Delegate event for communicate with LiveContainer (通知用 ~ 通知確認動作清除 LiveContainer 點擊動作)
        public delegate void CyclicScrollerBubbleToLiveContainer(string ProcessCode);
        public event CyclicScrollerBubbleToLiveContainer CyclicScrollerBubbleToLiveContainerEvent;

        public List<TouchInfo> touchinfoList = new List<TouchInfo>();

        //通知各 LiveContainer 函數~manipulation 事件或者為點擊展開事件
        void SendInfoToLiveContainer(TouchorManipulation Triggerevent)
        {
            if (Triggerevent == TouchorManipulation.TouchEvent)
            {
                if (touchinfoList.Count != 0)
                {
                    for (int index = 0; index < touchinfoList.Count; index++)
                    {
                        //for (int count = 0; count < ExtraUnitGridList.Count; count++)
                        {
                            int count = touchinfoList[index].TouchIndex - 1;
                            if (touchinfoList[index].TouchIndex == ExtraUnitGridList[count].Get_Set_MonitorIndex)
                            {
                                if (CheckExtendIsLegal(count))
                                {
                                    //判斷是否可以展開?
                                    if (ExtraUnitGridList[count].Get_Set_BlockControlMode == ExtraUnitGrid.ControlMode.CanExtend ||
                                        ExtraUnitGridList[count].IsUsing == 0)
                                    {
                                        //將點擊到的最上層物件加到MainWindow
                                        AddExtraUnitGridListInToMainWindow(count);
                                        AddExtraUnitGridListInToMainWindow(count - 1);
                                        AddExtraUnitGridListInToMainWindow(count + 1);

                                        //加載DetailViewer
                                        ExtraUnitGridList[count].BorderUp.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;

                                        ExtraUnitGridList[count].BorderUp.Child = AddDetailViewer(touchinfoList[index].TouchIndex, touchinfoList[index].IndexofEvent, touchinfoList[index].IndexofPic);
                                        ExtraUnitGridList[count].ExtendFunction();

                                        //寫入文字
                                        ExtraUnitGridList[count].textblock.Text = ((LiveContainer)uxMyStackPanel.Children[touchinfoList[index].TouchIndex]).uxYearStr.Text;
                                        ExtraUnitGridList[count].curDataIndex = -1;

                                        if (count + 1 < ExtraUnitGridList.Count)
                                        {
                                            ThumbnailContainer thumbnailControl = new ThumbnailContainer();
                                            List<string> folderPaths = new List<string>();

                                            folderPaths = GetThumbnailControl(touchinfoList[index].TouchIndex + 1);
                                            thumbnailControl.ImgPath = MediaUtilties.GetImageFromFolders(folderPaths.ToArray());
                                            ExtraUnitGridList[count + 1].BorderUp.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                                            ExtraUnitGridList[count + 1].BorderUp.Child = thumbnailControl;

                                            ExtraUnitGridList[count + 1].textblock.Text = ((LiveContainer)uxMyStackPanel.Children[touchinfoList[index].TouchIndex + 1]).uxYearStr.Text;
                                            ExtraUnitGridList[count + 1].curDataIndex = touchinfoList[index].TouchIndex + 1;
                                            ExtraUnitGridList[count + 1].ShrinkFunction("Right");
                                        }
                                        if (count - 1 >= 0)
                                        {
                                            ThumbnailContainer thumbnailControl = new ThumbnailContainer();
                                            List<string> folderPaths = new List<string>();

                                            folderPaths = GetThumbnailControl(touchinfoList[index].TouchIndex - 1);
                                            thumbnailControl.ImgPath = MediaUtilties.GetImageFromFolders(folderPaths.ToArray());
                                            ExtraUnitGridList[count - 1].BorderUp.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                                            ExtraUnitGridList[count - 1].BorderUp.Child = thumbnailControl;

                                            ExtraUnitGridList[count - 1].textblock.Text = ((LiveContainer)uxMyStackPanel.Children[touchinfoList[index].TouchIndex - 1]).uxYearStr.Text;
                                            ExtraUnitGridList[count - 1].curDataIndex = touchinfoList[index].TouchIndex - 1;
                                            ExtraUnitGridList[count - 1].ShrinkFunction("Left");
                                        }
                                        CheckDisplayRange();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else if (Triggerevent == TouchorManipulation.ManipulationEvent)
            {
                this.Dispatcher.BeginInvoke(CyclicScrollerBubbleToLiveContainerEvent, "Manipulation");
            }

            touchinfoList.Clear();
        }

        private bool CheckExtendIsLegal(int index)
        {
            bool result = true;
            index += 1;
            //判斷右邊
            if (index + 2 < ExtraUnitGridList.Count)
            {
                if (ExtraUnitGridList[index + 2].ShrinkStoryboardRun)
                    result = false;
            }
            //判斷左邊
            if (index - 2 >= 0)
            {
                if (ExtraUnitGridList[index - 2].ShrinkStoryboardRun)
                    result = false;
            }

            return result;
        }

        /// <summary>
        /// 通知各 LiveContainer 函數 自動輪播或者停止自動輪播事件通知
        /// </summary>
        /// <param name="ControlMode">當前模式</param>
        private void SendControlModeToLiveContainer(HistoryControlMode ControlMode)
        {
            if (ControlMode == HistoryControlMode.AutoRun)
            {
                this.Dispatcher.BeginInvoke(CyclicScrollerBubbleToLiveContainerEvent, "AutoRun");
            }
            else if (ControlMode == HistoryControlMode.Manual)
            {
                this.Dispatcher.BeginInvoke(CyclicScrollerBubbleToLiveContainerEvent, "Manual");
            }
        }

        private UIElement AddDetailViewer(int LiveContainerIndex, int indexofevent, int indexofpic)
        {
            //ImageBrush imagebrush = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/" + GlobalFunction.projectname + @";component/Data/Thumb/shadow_big.png", UriKind.RelativeOrAbsolute)));
            ImageBrush imagebrush = null;
            Grid gd = new Grid();
            int xy = 15;

            gd.Width = 810 + xy;
            gd.Height = 535 + 14;
            if (GlobalFunction.isSolutionUsing4K)
            {
                gd.Width *= 2;
                gd.Height *= 2;
            }

            //imagebrush.Stretch = Stretch.Uniform;
            gd.Background = Brushes.Transparent;
            gd.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            gd.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            gd.Margin = GlobalFunction.isSolutionUsing4K ? new Thickness(0, 50, 0, 0) : new Thickness(0);

            DetailViewer viewer = new DetailViewer(((LiveContainer)uxMyStackPanel.Children[LiveContainerIndex]).xmlData, LiveContainerIndex, indexofevent, indexofpic);
            viewer.IndexOfControl = LiveContainerIndex;
            viewer.Margin = new Thickness(0, 0, GlobalFunction.isSolutionUsing4K ? 8 : 4, GlobalFunction.isSolutionUsing4K ? 9 : 4);
            viewer.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            viewer.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            viewer.ChangeLanguageBtnTriggerEvent += new DetailViewer.ChangeLanguageBtnTriggerDelegate(viewer_ChangeLanguageBtnTriggerEvent);
            viewer.CloseBtnTriggerEvent += Viewer_CloseBtnTriggerEvent;
            //viewer.OnCloseEvent += new EventHandler<EventArgs>(viewer_OnCloseEvent);
            gd.Children.Add(viewer);

            return gd;
        }

        private void viewer_ChangeLanguageBtnTriggerEvent(int index, int useLangIndex)
        {
            LiveContainer lc = uxMyStackPanel.Children[index] as LiveContainer;

            if (useLangIndex == 0)
            {
                ExtraUnitGridList[index - 1].textblock.Text = lc.xmlData.yearlan1;
            }
            else if (useLangIndex == 1)
            {
                ExtraUnitGridList[index - 1].textblock.Text = lc.xmlData.yearlan2;
            }
            else if (useLangIndex == 2)
            {
                ExtraUnitGridList[index - 1].textblock.Text = lc.xmlData.yearlan3;
            }
            else if (useLangIndex == 3)
            {
                ExtraUnitGridList[index - 1].textblock.Text = lc.xmlData.yearlan4;
            }
        }


        private void Viewer_CloseBtnTriggerEvent(int indexOfCtrl)
        {
            SendInfoToMainWindow(indexOfCtrl);
        }

        private List<string> GetThumbnailControl(int LiveContainerIndex)
        {
            List<string> resultList = new List<string>();
            XmlData data = ((LiveContainer)uxMyStackPanel.Children[LiveContainerIndex]).xmlData;

            for (int i = 0; i < data.monthclassList.Count; i++)
            {
                resultList.Add(GlobalFunction.EventFileImgPath + data.monthclassList[i].imagepath);
            }

            return resultList;
        }

        //通知主視窗~可以將點擊開的物件縮回
        private void SendInfoToMainWindow(int index)
        {
            for (int count = 0; count < ExtraUnitGridList.Count; count++)
            {
                if (index == ExtraUnitGridList[count].Get_Set_MonitorIndex)
                {
                    //判斷是否可以縮小
                    if (ExtraUnitGridList[count].Get_Set_BlockControlMode == ExtraUnitGrid.ControlMode.Extend)
                    {
                        //回到原始大小
                        ExtraUnitGridList[count].ReturnToOriginalSize();
                        if (count + 1 < ExtraUnitGridList.Count)
                        {
                            ExtraUnitGridList[count + 1].BackSize("Right");
                        }
                        if (count - 1 >= 0)
                        {
                            ExtraUnitGridList[count - 1].BackSize("Left");
                        }
                    }
                }
            }
        }

        private void AddExtraUnitGridListInToMainWindow(int index)
        {
            if (index < 0 || index >= ExtraUnitGridList.Count)
            {
                return;
            }

            if (ExtraUnitGridList[index].IsUsing == 0)
            {
                ExtraUnitGridList[index].IsUsing = 1;
                if (!uxMainWindow.Children.Contains(ExtraUnitGridList[index]))
                {
                    uxMainWindow.Children.Add(ExtraUnitGridList[index]);
                }
            }
            else
            {
                ExtraUnitGridList[index].IsUsing = 2;
            }
        }

        //接收到~來自各LiveContainer 的通知
        void ReceiveFromLiveContainerInfo(string ProcessCode, int index, int indexofevent, int indexofpic)
        {
            if (ProcessCode == "TouchDown")
            {
                TouchInfo tif = new TouchInfo(index, indexofevent, indexofpic);

                touchinfoList.Add(tif);
                //檢查 TouchInfo 是否有重複的索引
                //檢查先被點擊的兩旁是否有被點擊~如果有被點擊則點擊無效~將該點擊濾掉
                touchinfoList = FilterTouchInfo(touchinfoList);
                //排列處理順序由小至大
                if (touchinfoList.Count > 1)
                {
                    touchinfoList = ArrangeTouchInfo(touchinfoList);
                }
            }
            else if (ProcessCode == "Load Complete")
            {
                if (RunHomePageAnimation)
                {
                    hp.AddLoadCount();
                    //OnDataLoadCompeleted?.Invoke(this,null);
                }
            }
        }

        //接收來自 ExtraUnitGrid 的通知
        void ExtraGrid_ExtraUnitGridBubbleToCyclicScrollerEvent(string ProcessCode, int index)
        {
            if (ProcessCode == "Change")
            {
                //通知主視窗~可以將點擊開的物件縮回
                ExtraUnitGridList[index].ShrinkStoryboardRun = true;
                SendInfoToMainWindow(index);
            }
            else if (ProcessCode == "Remove")
            {
                //移除該物件~先判斷該物件的兩邊的IsUsing已經被False
                if (ExtraUnitGridList[index].IsUsing == 0)
                {
                    uxMainWindow.Children.Remove(ExtraUnitGridList[index]);
                }
                if (index + 1 > 0 && index + 1 < ExtraUnitGridList.Count)
                {
                    ExtraUnitGridList[index + 1].ShrinkStoryboardRun = false;
                }
                CheckDisplayRange();
            }
        }

        /// <summary>
        /// 1.檢查 TouchInfo 是否有重複的索引
        /// 2.檢查先被點擊的兩旁是否有被點擊~如果有被點擊則點擊無效~將該點擊濾掉
        /// </summary>
        /// <param name="tif">來源</param>
        private List<TouchInfo> FilterTouchInfo(List<TouchInfo> tifList)
        {
            List<TouchInfo> resultList = new List<TouchInfo>();
            int totalcount = tifList.Count;

            for (int count = 0; count < totalcount; count++)
            {
                int currentindex = tifList[count].TouchIndex;

                if (!IsExistCount(currentindex, resultList))
                {
                    //不存在則新增
                    resultList.Add(tifList[count]);
                }
            }
            return resultList;
        }

        /// <summary>
        /// 排列處理順序由小至大
        /// </summary>
        /// <param name="touchinfoList">來源</param>
        /// <returns></returns>
        private List<TouchInfo> ArrangeTouchInfo(List<TouchInfo> tifList)
        {
            List<TouchInfo> resultList = new List<TouchInfo>();
            List<int> Arrange = new List<int>();

            for (int count = 0; count < tifList.Count; count++)
            {
                Arrange.Add(tifList[count].TouchIndex);
            }
            Arrange.Sort();

            for (int i = 0; i < Arrange.Count; i++)
            {
                for (int j = 0; j < tifList.Count; j++)
                {
                    if (Arrange[i] == tifList[j].TouchIndex)
                    {
                        resultList.Add(tifList[j]);
                    }
                }
            }

            return resultList;
        }

        private bool IsExistCount(int currentindex, List<TouchInfo> resultList)
        {
            bool resultbool = false;
            int resultListCount = resultList.Count;

            for (int count = 0; count < resultListCount; count++)
            {
                if (currentindex == resultList[count].TouchIndex)
                {
                    return true;
                }
                //兩旁也要濾掉
                if ((currentindex - 1) == resultList[count].TouchIndex)
                {
                    return true;
                }
                if ((currentindex + 1) == resultList[count].TouchIndex)
                {
                    return true;
                }
            }

            return resultbool;
        }
    }
}
