using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.Drawing;
using SPC.Kiosk.Base;
using SPC.Kiosk.Common;
using System.Windows.Threading;
using SPC.Kiosk.Popup.Model;
using SPC.Kiosk.Popup.ViewModel;
using System.Windows.Media.Animation;

namespace SPC.Kiosk.Popup
{
    /// <summary>
    /// HappyPointCertify.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class HappyPointCertify : Window 
    {
        #region [  Members  ]
        private int ScreenNo { get; set; } = 0;
        private VmHappyPointCertify ViewModel { get; set; }
        private bool ShowLanguageButton { get; set; }
        private bool ShowMemberHistoryItems { get; set; }
        private ParentPage PopupParentPage { get; set; } = ParentPage.EmptyPage;
        #endregion Members

        #region [ Ctor ]
        /// <summary>
        /// Ctor
        /// </summary>
        public HappyPointCertify(bool _showLanguageButton = true, bool _showMemberHistoryItems = true, ParentPage _popupParentPage = ParentPage.EmptyPage)
        {
            ShowLanguageButton = _showLanguageButton;
            ShowMemberHistoryItems = _showMemberHistoryItems;
            PopupParentPage = _popupParentPage;
            InitializeComponent();
            this.ContentRendered += HappyPointCertify_ContentRendered;
            this.Loaded += HappyPointCertify_Loaded;
            this.Left = Screen.AllScreens[ScreenNo].WorkingArea.Left;
            this.Top = Screen.AllScreens[ScreenNo].WorkingArea.Top;
            this.Width = Screen.AllScreens[ScreenNo].Bounds.Width;
            this.Height = Screen.AllScreens[ScreenNo].Bounds.Height;

        }



        #endregion Ctor

        #region [  Methods  ]
        private void OpenWindow()
        {
            var OpenAnimations = Animations.GetOpenAnimation(this.FrameBase
                                                           , OpenCloseAnimationType.FullSizeUp
                                                           , this.FrameBase.Height
                                                           , 0.5
                                                           , 0.5);
            if (OpenAnimations != null)
            {
                OpenAnimations.Completed += OpenAnimations_Completed;
                OpenAnimations.Begin();
            }
        }
        private void CloseWindow()
        {
            var CloseAnimation = Animations.GetCloseAnimation(this.FrameBase
                                                            , OpenCloseAnimationType.FullSizeDown
                                                            , this.FrameBase.Width
                                                            , 0.5
                                                            , 0.2);
            if (CloseAnimation != null)
            {
                CloseAnimation.Completed += CloseAnimation_Completed;
                CloseAnimation.Begin();
            }
        }
        private void ChangeWindow()
        {
            //this.Dispatcher.Invoke((Action)(() =>
            //{
            try
            {
                var _target = this.FrameData;
                var targetAnimation = new Storyboard();
                var centerX = _target.ActualWidth / 2;
                var centerY = _target.ActualHeight / 2;
                _target.RenderTransform = new ScaleTransform(1, 1, centerX, centerY);
                var flipXAni = new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(0.2)));
                Storyboard.SetTarget(flipXAni, _target);
                Storyboard.SetTargetProperty(flipXAni, new PropertyPath("RenderTransform.ScaleX"));
                targetAnimation.Children.Add(flipXAni);
                targetAnimation.Completed += TargetAnimation_Completed;
                targetAnimation.Begin();
            }
            catch
            {
            }
            //}));
        }

        private void TargetAnimation_Completed(object sender, EventArgs e)
        {
            if (this.ViewModel.CertifyWindow.Equals(CertifyWindowType.CertifyStart)
                && !this.ViewModel.ShowPhoneInput)
            {
                this.BarCode.IsEnabled = true;
                this.BarCode.Focus();
            }
            else
            {
                this.BarCode.IsEnabled = false;
            }
        }
        private void OpenOptionPopup()
        {
            this.ViewModel.TimerEnabled = false;
            try
            {
                var newOptions = new List<M_ItemOptionGroup>();
                foreach (var aOptionGroup in this.ViewModel.SelectedData.Option)
                {
                    newOptions.Add(aOptionGroup.Clone());
                }
                var newOpenOptionSelect = new OptionSelect(this.ViewModel.SelectedData.BaseTextBlock.LanguageData
                                                           , newOptions
                                                           , this.ViewModel.SelectedData.DataParameter.NormalBrush
                                                           , 1
                                                           , this.ViewModel.SelectedData.Price
                                                           , false);
                newOpenOptionSelect.ShowDialog();
                if (newOpenOptionSelect.DataContext is VmOptionSelect optionViewModel)
                {
                    this.ViewModel.GetOptionPopupReturn = optionViewModel.ReturnValue;
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "OpenOptionPopup", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
            finally
            {
                this.ViewModel.TimerEnabled = false;
            }
        }

        #endregion Methods

        #region [ Event Handlers ]
        private void OpenAnimations_Completed(object sender, EventArgs e)
        {
            if (this.ViewModel.CertifyWindow.Equals(CertifyWindowType.CertifyStart)
                && !this.ViewModel.ShowPhoneInput)
            {
                this.BarCode.IsEnabled = true;
                this.BarCode.Focus();
            }
            else
            {
                this.BarCode.IsEnabled = false;
            }
        }
        private void CloseAnimation_Completed(object sender, EventArgs e)
        {
            this.ContentRendered -= HappyPointCertify_ContentRendered;
            this.Loaded -= HappyPointCertify_Loaded;
            this.LostFocus -= HappyPointCertify_LostFocus;
            this.BarCode.PreviewKeyDown -= BarCode_PreviewKeyDown;
            this.BarCode.LostFocus -= BarCode_LostFocus;
            this.ChangeLanguage.MouseClicked -= ChangeLanguage_MouseClicked;
            this.ViewModel.Dispose();

            this.Close();
            
        }
        private void HappyPointCertify_ContentRendered(object sender, EventArgs e)
        {
            this.FrameBase.Width = 1300;
            this.FrameBase.Height = 1010;
            OpenWindow();
        }

        private void HappyPointCertify_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.DataContext is VmHappyPointCertify viewModel)
            {
                this.ViewModel = viewModel;
                this.ViewModel.PropertyChanged += ViewModel_PropertyChanged;
                this.ViewModel.LanguageButttonVisibel = ShowLanguageButton;
                this.ViewModel.MemberHistoryItemsGridHeight = ShowMemberHistoryItems ? 310d : 0d;
                this.ViewModel.TopGridMarginHeight = ShowMemberHistoryItems ? 0d : 120d;
                this.ViewModel.PopupWidth = this.FrameBase.Width;
                this.ViewModel.IsTimeoutPopup = false;
                this.ViewModel.PopupParentPage = PopupParentPage;
            }
            this.LostFocus += HappyPointCertify_LostFocus;
            this.BarCode.PreviewKeyDown += BarCode_PreviewKeyDown;
            this.BarCode.LostFocus += BarCode_LostFocus;
            this.ChangeLanguage.MouseClicked += ChangeLanguage_MouseClicked;
            this.FrameBase.Width = 0;
            this.FrameBase.Height = 0;
        }

        private void HappyPointCertify_LostFocus(object sender, RoutedEventArgs e)
        {
            this.Focus();
        }

        private void ChangeLanguage_MouseClicked(object sender, RoutedEventArgs e)
        {
            this.ViewModel.TimerEnabled = false;
            try
            {
                M_PopupReturn result = null;
                var newLanguageSelector = new LanguageSelector(this.ViewModel.ShowLanguageType);
                newLanguageSelector.ShowDialog();
                if (newLanguageSelector.DataContext is VmLanguageSelector viewModel)
                {
                    result = viewModel.ReturnValue;
                }
                newLanguageSelector = null;
                if (result is M_PopupReturn)
                {
                    if (result.TimeOut)
                    {
                        this.ViewModel.ReturnValue = result;
                        CloseWindow();
                    }
                    else
                    {
                        this.ViewModel.ShowLanguageType = result.ReturnLanguage;
                        this.ViewModel.TimerEnabled = true;
                    }
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "ChangeLanguage_MouseClicked", "Fail", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }

        private void BarCode_LostFocus(object sender, RoutedEventArgs e)
        {
            this.BarCode.Focus();
        }

        private void BarCode_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (sender is System.Windows.Controls.TextBox textBox 
                && (e.Key.Equals(Key.Enter) || e.Key.Equals(Key.Return))
                && !string.IsNullOrEmpty(textBox.Text))
            {
                this.ViewModel.ReadBarCode = textBox.Text.Trim();
                textBox.Text = string.Empty;
            }
        }
        private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "CanWindowClose":
                    if (this.ViewModel.CanWindowClose)
                    {
                        CloseWindow();
                    }
                    break;
                case "OpenOptionPopup":
                    if (this.ViewModel.OpenOptionPopup)
                    {
                        OpenOptionPopup();
                    }
                    break;
                case "ShowPhoneInput":
                    ChangeWindow();
                    break;
                case "CertifyWindow":
                    ChangeWindow();
                    break;


            }
        }



        #endregion Event Handlers

        private void OrderHistory_MouseClicked(object sender, RoutedEventArgs e)
        {

        }
    }


}
