using Cosmos.BaseFrame;
using Cosmos.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;
using System.ComponentModel;
using System.Windows.Input;
using SPC.Kiosk.Common;
using SPC.Kiosk.Base;
using System.Windows.Media.Animation;
using System.Windows;
using System.Collections.ObjectModel;
using System.Windows.Forms;
using SPC.Kiosk.Start.Model;
using System.Text.RegularExpressions;

namespace SPC.Kiosk.Start.ViewModel
{
    /// <summary>
    /// Test View Model
    /// </summary>
    public class VmStartViewModel : ViewModelBase
    {
        #region [  Members  ]

        public SupportLanguageType ShowLanguageType
        {
            get { return CommonValue.CommonLanguageType; }
            set { CommonValue.CommonLanguageType = value; PropertyChange("ShowLanguageType"); }
        }
        public string TitIeImage { get; set; } = ResourceManager.GetCDPimagePath("intro_bimg.png");

        public string CloseImage { get; set; } = ResourceManager.GetNximagePath("btn_close.png");

        public string IntroTop { get; set; } = ResourceManager.GetCDPimagePath("블루투스인형1.jpg");

        public string IntroBottom { get; set; } = ResourceManager.GetCDPimagePath("블루투스인형2.jpg");

        public ObservableCollection<M_MediaRollItem> MediaRollItems { get; set; }
        
        public int ScreenNo { get; set; }
        public Size ScreenSize { get; set; }
        public string FirstMedia { get; set; }

        public ICommand BaseToTradeCommad { get; protected set; } = null;
        public ICommand RollMediaCommand { get; protected set; } = null;
        public ICommand ItemDropedCommand { get; protected set; } = null;
        public ICommand ListItemDropCommand { get; protected set; } = null;
        public ICommand ListCircleClickCommand { get; protected set; } = null;
        public ICommand OpenPopupCommand { get; protected set; } = null;
        public ICommand WaitPopupCommand { get; protected set; } = null;

        public ICommand NumericPadOkCommand { get; protected set; } = null;

        private bool toggleSwitch = false;
        public bool ToggleSwitch
        {
            get { return toggleSwitch; }
            set { toggleSwitch = value; PropertyChange("ToggleSwitch"); }
        }
        private int testItemPageNo;
        public int TestItemPageNo
        {
            get
            {
                return testItemPageNo;
            }
            set
            {
                testItemPageNo = value;
                PropertyChange("TestItemPageNo");
            }
        }
        private ObservableCollection<M_ItemData> testItems;
        public ObservableCollection<M_ItemData> TestItems
        {
            get
            {
                return testItems;
            }
            set
            {
                testItems = value;
                PropertyChange("TestItems");
            }
        }
        private int defaultSelectedItem;
        public int DefaultSelectedItem
        {
            get
            {
                return defaultSelectedItem;
            }
            set
            {
                defaultSelectedItem = value;
                PropertyChange("DefaultSelectedItem");
            }
        }
        private int defaultSelectedPageNo;
        public int DefaultSelectedPageNo
        {
            get
            {
                return defaultSelectedPageNo;
            }
            set
            {
                defaultSelectedPageNo = value;
                PropertyChange("DefaultSelectedPageNo");
            }
        }
        public int SelectedColumnCount { get; set; }
        public int SelectedRowCount { get; set; }


        private ObservableCollection<M_ItemData> selectedItems;
        public ObservableCollection<M_ItemData> SelectedItems
        {
            get
            {
                return selectedItems;
            }
            set
            {
                selectedItems = value;
                PropertyChange("SelectedItems");
            }
        }

        public List<M_Language> PreviousText { get; set; }
        public List<M_Language> NextText { get; set; }
        public List<M_Language> PopupText { get; set; }
        public List<M_Language> ExistText { get; set; }
        public List<M_Language> ToggleText { get; set; }
        public List<M_Language> TradeHeaderText { get; set; }

        public List<M_Language> OkText { get; set; }
        public List<M_Language> CancelText { get; set; }
        public List<M_Language> InputMobileNumberMessage { get; set; }

        private string inputNumbers;
        public  string InputNumbers
        {
            get
            {
                return inputNumbers;
            }
            set
            {
                inputNumbers = value;
                PropertyChange("InputNumbers");
            }
        }

        #endregion Members

        #region [ Ctor ]
        public VmStartViewModel()
        {
            ScreenNo = 0;
            ScreenSize = new Size(0,0);
            InitViewModel();
        }
        public VmStartViewModel(int _screenNo,Size _screensize)
        {
            ScreenNo = _screenNo;
            ScreenSize = _screensize;
            InitViewModel();
        }

        #endregion Ctor

        #region [  Methods  ]

        private void InitViewModel()
        {
            var waitWindow = new WaitWindow();
            waitWindow.ShowWaitWindow();
            try
            {
                SelectedColumnCount = 6;
                SelectedRowCount = 1;

                BaseToTradeCommad = new Command(BaseToTradeCommandHandler);
                RollMediaCommand = new Command(RollMediaCommandHandler);
                ItemDropedCommand = new Command(ItemDropedCommandHandler);
                ListItemDropCommand = new Command(ListItemDropCommandHandler);
                ListCircleClickCommand = new Command(ListCircleClickCommandHandler);
                OpenPopupCommand = new Command(OpenPopupCommandHandler);
                WaitPopupCommand = new Command(WaitPopupCommandHandler);
                NumericPadOkCommand = new Command(NumericPadOkCommandHandler);
                TitIeImage = ResourceManager.GetCDPimagePath("intro_bimg.png");
                CloseImage = ResourceManager.GetNximagePath("btn_close.png");
                FirstMedia = ResourceManager.GetCDPmediaPath("CF1.wmv");

                MediaRollItems = new ObservableCollection<M_MediaRollItem>
                {
                    new M_MediaRollItem() { Type = MediaType.Image, MediaPath = ResourceManager.GetCDPimagePath("블루투스인형2.jpg"), RunnigSeconds = 10 },
                    new M_MediaRollItem() { Type = MediaType.VOD, MediaPath = ResourceManager.GetCDPmediaPath("CF1.wmv"), RunnigSeconds = 48 },
                    new M_MediaRollItem() { Type = MediaType.VOD, MediaPath = ResourceManager.GetCDPmediaPath("CF2.wmv"), RunnigSeconds = 39 },
                };

                PreviousText = Languages.GetMessages("CommonPrevious");
                NextText = Languages.GetMessages("CommonNext");
                PopupText = Languages.GetMessages("CommonPopup");
                ExistText = Languages.GetMessages("CommonExist");
                ToggleText = Languages.GetMessages("CommonToggle");
                TradeHeaderText = Languages.GetMessages("TradeHeader");
                InputMobileNumberMessage = Languages.GetMessages("MobileNumberMessage");
                OkText = Languages.GetMessages("CommonOK");
                CancelText = Languages.GetMessages("CommonCancel");

                this.PropertyChanged += VmStartViewModel_PropertyChanged;
                

            }
            catch
            {
                throw;
            }
            finally
            {
                waitWindow.CloseWaitWindow();
            }
        }


        private void VmStartViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "ToggleSwitch":
                    ShowLanguageType = ToggleSwitch ? SupportLanguageType.en : SupportLanguageType.ko;
                    break;
                default:
                    break;
            }
        }



        private List<M_ItemData> GetEmptyItems(int _emptyCount)
        {
            List<M_ItemData> result = null;

            try
            {
                result = new List<M_ItemData>();
                for (int i = 0; i < _emptyCount; i++) result.Add(GetAnEmptyItem(i));
                return result;
            }
            catch
            {
                result = null;
            }
            return result;

        }
        private M_ItemData GetSelectData(int _index, M_ItemData _sourceData)
        {
            M_ItemData result = null;
            try
            {
                result = new M_ItemData
                {
                    Index = _index,
                    ItemCode = _sourceData.ItemCode,
                    Category1 = "Select",
                    DataParameter  = _sourceData.DataParameter
                };
                result.DataParameter.Width = 100;
                result.DataParameter.Height = 100;
                result.DataParameter.DragEnable = false;
                result.DataParameter.DragCursorImage = string.Empty;
                result.DataParameter.ClickAnimationType = ButtonAnimationType.None;
                result.DataParameter.CircleSize = 30;
                result.DataParameter.CircleBackBrush = "Black";
                result.DataParameter.CircleTextBruch = "White";
                result.DataParameter.CircleText = "X";
            }
            catch
            {

                result = null;
            }
            return result;
        }
        private M_ItemData GetAnEmptyItem(int _index)
        {
            M_ItemData result = null;
            try
            {
                result= new M_ItemData
                {
                    Index = _index,
                    ItemCode = "EmptyItem",
                    Category1 = "Empty",
                    DataParameter = new M_AnimationButton
                    {
                        NormalBrush = "Gray",
                        DownBrush = "Gray",
                        DragEnable = false,
                        Width = 100,
                        Height = 100,
                        Switch = false,
                        AutoToggle = false,
                        ClickAnimationType = ButtonAnimationType.None,
                        CircleBackBrush = "Transparent",
                        CircleTextBruch = "Transparent",
                        CircleText = string.Empty,
                    }
                };
            }
            catch 
            {

                result = null;
            }
            return result;
        }
        private List<M_ItemData> GetItemImages(List<M_ItemData> m_ItemDatas)
        {
            List<M_ItemData> result = m_ItemDatas;

            try
            {
                var itemFiles = ResourceManager.GetItemImages("*.png");
                if (result ==null) result= new List<M_ItemData>();
                result.Clear();
                int index = 0;
                foreach (var aItemFles in itemFiles)
                {
                    var aFile = new FileInfo(aItemFles);
                    if (Regex.IsMatch(aFile.Name.Replace(aFile.Extension, ""), "^[0-9]"))
                    {
                        result.Add(new M_ItemData()
                        {
                            Index = index,
                            ItemCode = aFile.Name.Replace(aFile.Extension, ""),
                            Category1 = "All",
                            DataParameter = new M_AnimationButton
                            {
                                NormalBrush = aItemFles,
                                DownBrush = aItemFles,
                                DragCursorImage = aItemFles,
                                Width = 100,
                                Height = 100,
                                BrushStretch = Stretch.Fill,
                                Switch = false,
                                AutoToggle = false,
                                DragEnable = true,
                                DragCursorHotSpot = HotSpotType.Center,
                                ClickAnimationType = ButtonAnimationType.SizeUp,
                                CircleBackBrush = "Transparent",
                                CircleTextBruch = "Transparent",
                                CircleText = string.Empty
                            },
                            BaseTextBlock = new M_TextBlock()
                            {
                                LanguageData = new List<M_Language> {
                                new M_Language{ Type = SupportLanguageType.en, LanguageData = aFile.Name.Replace(aFile.Extension, "")},
                                new M_Language{ Type = SupportLanguageType.ko, LanguageData = aFile.Name.Replace(aFile.Extension, "")}
                                },
                                TextSize = 14,
                                TextBrush = "White",
                                TextWeight = FontWeights.Bold
                            },
                            AdditionTextBlock = new M_TextBlock()
                            {
                                LanguageData = new List<M_Language> {
                                    new M_Language{ Type = SupportLanguageType.en, LanguageData = string.Format("￦{0:#,##0}", 3001)},
                                    new M_Language{ Type = SupportLanguageType.ko, LanguageData = string.Format("￦{0:#,##0}", 3000)}
                                    },
                                TextSize = 16,
                                TextBrush = "LightPink",
                                TextWeight = FontWeights.Bold,
                            },

                        });
                        index++;
                    }
                }
                return result;
            }
            catch 
            {
                result = null;
            }
            return result;
        }

        private void DataModelInit()
        {
            var waitWindow = new WaitWindow();
            waitWindow.ShowWaitWindow();
            try
            {
                ToggleSwitch = false;
                TestItems = new ObservableCollection<M_ItemData>(GetItemImages(null));
                TestItemPageNo = 0;
                SelectedItems = new ObservableCollection<M_ItemData>(GetEmptyItems(1));
                DefaultSelectedItem = 0;
                DefaultSelectedPageNo = 0;

            }
            catch
            {
                throw;
            }
            finally
            {
                waitWindow.CloseWaitWindow();
            }

        }

        #endregion Methods

        #region Event Handlers
        private void NumericPadOkCommandHandler(object _param)
        {
            if (!string.IsNullOrEmpty(InputNumbers))
            {
                if (InputNumbers.Length < 11)
                {
                    KioskMessageBox.TimeMessageBox(ScreenNo
                                          , ScreenSize
                                          , null
                                          , null
                                          , Languages.GetMessages("TimePopupMessage")
                                          , OpenCloseAnimationType.GotoUp
                                          , OpenCloseAnimationType.GotoDown, 0.5, 0.2, 2);
                }
                else if (InputNumbers.Length.Equals(11))
                {
                    InputNumbers = string.Empty;
                }
            }
        }

        private void ListItemDropCommandHandler(object _param)
        {
            if (_param != null)
            {
                var dropedItem = _param as M_ItemDropEventArgs;
                var sourceButton = dropedItem.SourceObject as AnimationButton;
                var targetButton = dropedItem.TargetObject as AnimationButton;
                var targetData = targetButton.DataParameter as M_ItemData;
                var sourceData = sourceButton.DataParameter as M_ItemData;
                var selectSourceData = TestItems.Where(r => r.Equals(sourceData)).FirstOrDefault();
                var targetIndex = SelectedItems.IndexOf(targetData);
                if (targetIndex > -1)
                {
                    var newSelectItem = GetSelectData(targetData.Index, sourceData);
                    SelectedItems[targetIndex] = newSelectItem;
                    targetButton.DataParameter = newSelectItem;
                    var defaultItem = SelectedItems.Where(r => r.ItemCode.Equals("EmptyItem")).FirstOrDefault();
                    if (defaultItem == null)
                    {
                        SelectedItems.Add(GetAnEmptyItem(SelectedItems.Count));
                        SelectedItems = new ObservableCollection<M_ItemData>(SelectedItems.ToList()); 
                    }
                    DefaultSelectedItem = SelectedItems.IndexOf(SelectedItems.Where(r => r.ItemCode.Equals("EmptyItem")).FirstOrDefault());
                    DefaultSelectedPageNo = DefaultSelectedItem / (SelectedColumnCount * SelectedRowCount);
                }
    
            }
        }
        private void ListCircleClickCommandHandler(object _param)
        {
            var targetButton = _param as AnimationButton;
            var targetData = targetButton.DataParameter as M_ItemData;
            var targetIndex = SelectedItems.IndexOf(targetData);
            if (targetIndex > -1)
            {
                var newDeletedItem = GetAnEmptyItem(targetIndex);
                SelectedItems[targetIndex] = newDeletedItem;
                targetButton.DataParameter = newDeletedItem;
                DefaultSelectedItem = SelectedItems.IndexOf(SelectedItems.Where(r => r.ItemCode.Equals("EmptyItem")).FirstOrDefault());
            }
        }

        private void OpenPopupCommandHandler(object obj)
        {
            var dialogResult = MessageBoxResult.None;
            while (dialogResult.Equals(MessageBoxResult.None))
            {
                dialogResult = KioskMessageBox.ShowMessageBox(ScreenNo
                                                            , ScreenSize
                                                            , Languages.GetMessages("PopupHeader")
                                                            , null
                                                            , Languages.GetMessages("PopupMessage")
                                                            , MessageBoxButton.YesNo
                                                            , OpenCloseAnimationType.GotoUp
                                                            , OpenCloseAnimationType.GotoDown, 0.5, 0.2);
            }

        }
        private void WaitPopupCommandHandler(object obj)
        {
            KioskMessageBox.TimeMessageBox(ScreenNo
                                          , ScreenSize
                                          , null
                                          , null
                                          , Languages.GetMessages("TimePopupMessage")
                                          , OpenCloseAnimationType.GotoLeft
                                          , OpenCloseAnimationType.GotoRight, 0.5, 0.2, 3);
        }

        private void BaseToTradeCommandHandler(object _param)
        {
            DataModelInit();
        }
        private void RollMediaCommandHandler(object _param)
        {
            DataModelInit();
        }
        private void ItemDropedCommandHandler(object _param)
        {
            if (_param is M_ItemDropEventArgs dropedItem)
            {
                var targetButton = dropedItem.TargetObject as AnimationButton;
                targetButton.CircleText = (int.Parse(targetButton.CircleText) + 1).ToString() ;
            }
        }
       
        #endregion Event Handlers
    }

}
