using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using HistoryWallEditTool.JsonFile;
using System.IO;

namespace HistoryWallEditTool.ControlsForData
{
    public partial class EventCreator : UserControl
    {
        //當前焦點索引值
        private int curItemIndex = -1;
        //通知前端改變了選擇的項目
        public delegate void SelectChangeInfoDelegate(int index);
        public event SelectChangeInfoDelegate SelectChangeInfoEvent;
        //通知前端某物件被刪除了
        public delegate void DeleteEventInfoDelegate();
        public event DeleteEventInfoDelegate DeleteEventInfoEvent;

        //EventCreator 主或者子分類
        private EventCreatorClass curEventClass = EventCreatorClass.MainEvent;
        //當前語系
        private CurrentEditLanguage curLanguage = CurrentEditLanguage.LanguageOne;
        //當前語系方向
        private FlowDirection curLanguageDir = FlowDirection.LeftToRight;
        //判斷焦點
        private bool unControlFlag = false;

        #region icon
        private void AddCategoryToolBar()
        {
            uxAddBtn.IconData = GlobalFunction.AddBtnData;
            uxDeleteBtn.IconData = GlobalFunction.DeleteBtnData;
            uxUpBtn.IconData = GlobalFunction.MoveUpBtnData;
            uxDownBtn.IconData = GlobalFunction.MoveDownBtnData;
        }
        #endregion

        #region 由主視窗來判斷該焦點是否要移除
        public void MainCheckFocus()
        {
            unControlFlag = true;
        }

        public void MainRemoveFocus()
        {
            if (unControlFlag)
            {
                //判斷當前選擇的項目是否在 Listbox 範圍內
                if (curItemIndex < uxItemListBox.Items.Count && curItemIndex >= 0)
                {
                    //轉移該控制項的焦點
                    UserEventItem cwcdc = uxItemListBox.Items[curItemIndex] as UserEventItem;

                    if (cwcdc != null)
                    {
                        cwcdc.LetLostFocus();
                    }
                }
            }
        }
        #endregion

        private bool AddJsonData()
        {
            if (curEventClass == EventCreatorClass.MainEvent)
            {
                EventGroup eg = new EventGroup();

                MainContainer.hweventJson.EventGroups.Add(eg);
            }
            else if (curEventClass == EventCreatorClass.SubEvent)
            {
                if (MainContainer.mainEventIndex == -1)
                {
                    return false;
                }
                ListDate ld = new ListDate();

                MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates.Add(ld);
            }
            return true;
        }

        private void DeleteJsonData(int index)
        {
            if (curEventClass == EventCreatorClass.MainEvent)
            {
                MainContainer.mainEventIndex = -1;
                //有圖片的資料夾的話要順便刪除掉
                for (int i = 0; i < MainContainer.hweventJson.EventGroups[index].ListDates.Count; i++)
                {
                    string deleteFolderName = MainContainer.hweventJson.EventGroups[index].ListDates[i].ImagePath;
                    if (deleteFolderName != "")
                    {
                        if (Directory.Exists(MainContainer.imgFolderName + deleteFolderName))
                        {
                            Directory.Delete(MainContainer.imgFolderName + deleteFolderName, true);
                        }
                    }
                }

                MainContainer.hweventJson.EventGroups.RemoveAt(index);
            }
            else if (curEventClass == EventCreatorClass.SubEvent)
            {
                MainContainer.subEventIndex = -1;
                //有圖片的資料夾的話要順便刪除掉
                string deleteFolderName = MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates[index].ImagePath;
                if (deleteFolderName != "")
                {
                    if (Directory.Exists(MainContainer.imgFolderName + deleteFolderName))
                    {
                        Directory.Delete(MainContainer.imgFolderName + deleteFolderName, true);
                    }
                }
                MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates.RemoveAt(index);
            }
        }

        /// <summary>
        /// 兩個資料位置互換
        /// 使用方式 :  fromIndex 值必須大於 toIndex
        /// </summary>
        /// <param name="fromIndex">後面的索引值</param>
        /// <param name="toIndex">前面的索引值</param>
        private void MoveJsonMainData(int fromIndex, int toIndex)
        {
            if (curEventClass == EventCreatorClass.MainEvent)
            {
                EventGroup eg = MainContainer.hweventJson.EventGroups[fromIndex];

                MainContainer.hweventJson.EventGroups.Insert(toIndex, eg);
                MainContainer.hweventJson.EventGroups.RemoveAt(fromIndex + 1);
            }
            else if (curEventClass == EventCreatorClass.SubEvent)
            {
                ListDate ld = MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates[fromIndex];

                MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates.Insert(toIndex, ld);
                MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates.RemoveAt(fromIndex + 1);
            }
        }

        private UserEventItem GetUserItemForAdd()
        {
            if (curEventClass == EventCreatorClass.MainEvent)
            {
                return new UserEventItem(ControlMode.Create, curEventClass, MainContainer.hweventJson.EventGroups.Count - 1, curLanguage, curLanguageDir);
            }
            else if (curEventClass == EventCreatorClass.SubEvent)
            {
                return new UserEventItem(ControlMode.Create, curEventClass, MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates.Count - 1, curLanguage, curLanguageDir);
            }

            return null;
        }

        #region 新增, 刪除, 上移, 下移, 切換項目
        private void SetUpDownBtnShow(int curItemIndex)
        {
            if (curItemIndex == -1)
            {
                uxUpBtn.IsEnabled = false;
                uxDownBtn.IsEnabled = false;
            }
            else
            {
                uxUpBtn.IsEnabled = true;
                uxDownBtn.IsEnabled = true;

                if (curItemIndex <= 0)
                {
                    uxUpBtn.IsEnabled = false;
                }

                if (curItemIndex >= uxItemListBox.Items.Count - 1)
                {
                    uxDownBtn.IsEnabled = false;
                }
            }
        }

        private void uxItemListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (curItemIndex != -1)
            {
                if (curItemIndex < uxItemListBox.Items.Count)
                {
                    UserEventItem cwcdc = uxItemListBox.Items[curItemIndex] as UserEventItem;

                    if (cwcdc != null)
                    {
                        cwcdc.textBlock.IsEnabled = false;
                        cwcdc.LetLostFocus();
                    }
                }
            }
            unControlFlag = false;
            curItemIndex = uxItemListBox.SelectedIndex;

            //如果不是失去焦點的改變~則代表有個項目被點擊~載入該項目的子資料
            if (curItemIndex != -1)
            {
                UserEventItem cwcdc = uxItemListBox.Items[curItemIndex] as UserEventItem;

                if (cwcdc != null)
                {
                    cwcdc.textBlock.IsEnabled = true;
                }

                this.Dispatcher.BeginInvoke(SelectChangeInfoEvent, DispatcherPriority.Background, curItemIndex);
            }
            //重新設定上下移動的 radiobtn 顯示的狀況
            SetUpDownBtnShow(curItemIndex);
        }

        private bool CheckSubDataExist(int index)
        {
            bool result = false;

            if (curEventClass == EventCreatorClass.MainEvent)
            {
                if (MainContainer.hweventJson.EventGroups[index].ListDates.Count > 0)
                {
                    result = true;
                }
            }
            else if (curEventClass == EventCreatorClass.SubEvent)
            {
                if (MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates[index].Month != "" ||
                    MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates[index].TitleLan1 != "" ||
                    MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates[index].TitleLan2 != "" ||
                    MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates[index].Script1 != "" ||
                    MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates[index].Script2 != "" ||
                    MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates[index].ImagePath != "")
                    return true;
            }

            return result;
        }

        //事件區塊被刪除~重新排列編號
        private void ReArrangeListNumber()
        {
            for (int i = 0; i < uxItemListBox.Items.Count; i++)
            {
                UserEventItem cwcdc = uxItemListBox.Items[i] as UserEventItem;

                cwcdc.uxNumber.Text = (i + 1).ToString();
            }
        }

        private void ChangeListNumber(int indexOne, int indexTwo)
        {
            UserEventItem cwcdcOne = uxItemListBox.Items[indexOne] as UserEventItem;
            UserEventItem cwcdcTwo = uxItemListBox.Items[indexTwo] as UserEventItem;

            string oneNumber = cwcdcOne.uxNumber.Text;

            cwcdcOne.uxNumber.Text = cwcdcTwo.uxNumber.Text;
            cwcdcTwo.uxNumber.Text = oneNumber;
        }

        private void uxAddBtn_Click(object sender, RoutedEventArgs e)
        {
            if (curEventClass == EventCreatorClass.SubEvent)
            {
                if (MainContainer.mainEventIndex == -1)
                {
                    return;
                }
                else if (MainContainer.hweventJson.EventGroups[MainContainer.mainEventIndex].ListDates.Count >= 20)
                {
                    MessageBox.Show((string)FindResource("rejectStr"));
                    return;
                }
            }

            //Json 新增該筆資料
            if (AddJsonData())
            {
                UserEventItem cwcdc = GetUserItemForAdd();

                uxItemListBox.Items.Add(cwcdc);

                uxItemListBox.SelectedIndex = uxItemListBox.Items.Count - 1;
                uxItemListBox.ScrollIntoView(cwcdc);
                cwcdc.LetGetFocus();
            }
        }

        private void uxDeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            if (curItemIndex != -1)
            {
                bool deleteRun = true;
                //先確認是否有子資料~如果有再詢問~如果無~則直接將之刪除
                if (CheckSubDataExist(curItemIndex))
                {
                    TaskDialogMsg tdmsg = new TaskDialogMsg(curEventClass);

                    tdmsg.ShowDialog();
                    deleteRun = tdmsg.isCheck;
                }

                if (deleteRun)
                {
                    //Json 刪除該筆資料
                    DeleteJsonData(curItemIndex);
                    uxItemListBox.Items.RemoveAt(curItemIndex);
                    //重新排列編號
                    ReArrangeListNumber();
                    //通知前端~物件刪除
                    this.Dispatcher.BeginInvoke(DeleteEventInfoEvent, DispatcherPriority.Background);
                }
            }
        }

        private void uxUpBtn_Click(object sender, RoutedEventArgs e)
        {
            if (curItemIndex > 0)
            {
                UserEventItem cwcdc = uxItemListBox.Items[curItemIndex] as UserEventItem;

                if (cwcdc != null)
                {
                    //移除焦點~並儲存
                    cwcdc.LetLostFocus();
                    //Json 移動該筆資料
                    MoveJsonMainData(curItemIndex, curItemIndex - 1);
                    //當前視窗位置移動
                    int index = curItemIndex;

                    uxItemListBox.Items.RemoveAt(index);
                    uxItemListBox.Items.Insert(index - 1, cwcdc);
                    ChangeListNumber(index, index - 1);
                    uxItemListBox.ScrollIntoView(cwcdc);
                    uxItemListBox.SelectedIndex = index - 1;
                }
            }
        }

        private void uxDownBtn_Click(object sender, RoutedEventArgs e)
        {
            if (curItemIndex != -1 && curItemIndex < uxItemListBox.Items.Count - 1)
            {
                UserEventItem cwcdc = uxItemListBox.Items[curItemIndex] as UserEventItem;

                if (cwcdc != null)
                {
                    //移除焦點~並儲存
                    cwcdc.LetLostFocus();
                    //Json 移動該筆資料
                    MoveJsonMainData(curItemIndex + 1, curItemIndex);
                    //當前視窗位置移動
                    int index = curItemIndex;

                    uxItemListBox.Items.RemoveAt(index);
                    uxItemListBox.Items.Insert(index + 1, cwcdc);
                    ChangeListNumber(index, index + 1);
                    uxItemListBox.ScrollIntoView(cwcdc);
                    uxItemListBox.SelectedIndex = index + 1;
                }
            }
        }
        #endregion

        #region 由上層控制的函數
        public void ExtraSaveFunction(int willSaveIndex)
        {
            if (curItemIndex != -1 && curItemIndex < uxItemListBox.Items.Count)
            {
                UserEventItem cwcdc = uxItemListBox.Items[willSaveIndex] as UserEventItem;

                if (cwcdc != null)
                {
                    cwcdc.textBlock.IsEnabled = false;
                    cwcdc.LetLostFocus();
                }
            }
        }
        #endregion
    }
}
