using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SPC.Kiosk.Base;
using SPC.Kiosk.Common;
using SPC.Kiosk.PB.Model;
namespace SPC.Kiosk.PB
{
    /// <summary>
    /// MiniBasketItems.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MiniBasketItems : UserControl
    {
        #region [ Members ]
        /// <summary>
        /// ListItems
        /// </summary>
        public static readonly DependencyProperty ListItemsProperty =
                 DependencyProperty.Register(nameof(ListItems), typeof(ObservableCollection<M_BasketItem>), typeof(MiniBasketItems), new PropertyMetadata(null, new PropertyChangedCallback(OnListItemsPropertyChanged)));
        /// <summary>
        /// Command
        /// </summary>
        public static readonly DependencyProperty CommandProperty =
                 DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(MiniBasketItems), new UIPropertyMetadata(null));
        /// <summary>
        /// Vertical Scroll Offset
        /// </summary>
        public static readonly DependencyProperty VerticalOffsetProperty =
                 DependencyProperty.Register(nameof(VerticalOffset), typeof(double), typeof(MiniBasketItems), new PropertyMetadata(0d, new PropertyChangedCallback(OnVerticalOffsetPropertyChanged)));
        /// <summary>
        /// Display Language
        /// </summary>
        public static readonly DependencyProperty DisplayLanguagePropery =
                 DependencyProperty.Register(nameof(DisplayLanguage), typeof(SupportLanguageType), typeof(MiniBasketItems), new PropertyMetadata(SupportLanguageType.ko, new PropertyChangedCallback(OnDisplayLanguageProperyChanged)));


        private double mouseDownYposition = -1;
        private bool MoseDown = false;
        /// <summary>
        /// ListItems
        /// </summary>
        public ObservableCollection<M_BasketItem> ListItems
        {
            get { return (ObservableCollection<M_BasketItem>)GetValue(ListItemsProperty); }
            set { SetValue(ListItemsProperty, value); }
        }
        /// <summary>
        /// Command
        /// </summary>
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }
        /// <summary>
        /// VerticalOffset
        /// </summary>
        public double VerticalOffset
        {
            get { return (double)GetValue(VerticalOffsetProperty); }
            set { SetValue(VerticalOffsetProperty, value); }
        }
        /// <summary>
        /// Display Language
        /// </summary>
        public SupportLanguageType DisplayLanguage
        {
            get { return (SupportLanguageType)GetValue(DisplayLanguagePropery); }
            set { SetValue(DisplayLanguagePropery, value); }
        }

        #region [ RoutedEvent 'MouseClicked' ]

        /// <summary>
        /// MouseClicked Event
        /// </summary>
        public static readonly RoutedEvent MouseClickedEvent = EventManager.RegisterRoutedEvent(nameof(MouseClicked), RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MiniBasketItems));
        /// <summary>
        /// MouseClicked Routed Event Handler
        /// </summary>
        public event RoutedEventHandler MouseClicked
        {
            add { AddHandler(MouseClickedEvent, value); }
            remove { RemoveHandler(MouseClickedEvent, value); }
        }
        #endregion RoutedEvent 'MouseClicked'

        #endregion Members

        #region [ Ctor & Etc ]
        /// <summary>
        /// Ctor
        /// </summary>
        public MiniBasketItems()
        {
            InitializeComponent();
            this.Unloaded += MiniBasketItems_Unloaded;
        }

        #endregion Ctor & Etc

        #region [ Methods ]
        /// <summary>
        /// Raise MouseClicked Event
        /// </summary>
        private void RaiseMouseClickedEvent(object _sender)
        {
            //Command Excute 
            if (Command != null && Command.CanExecute(_sender))
            {
                Command.Execute(_sender);
            }
            RoutedEventArgs newEventArgs = new RoutedEventArgs(MiniBasketItems.MouseClickedEvent, _sender);
            RaiseEvent(newEventArgs);
        }
        private void FlipItem(FrameworkElement _target)
        {
            try
            {
                var targetAnimation = new Storyboard();
                var getAnimations = Animations.GetMoveAnimation(_target, OpenCloseAnimationType.GotoDown, _target.ActualHeight *-1, 0, 0.5, 1, 0.5);
                foreach (var aAnimation in getAnimations) targetAnimation.Children.Add(aAnimation);
                targetAnimation.Begin();
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "FlipItem()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        private void ItemsButtonCreate(object _listItems)
        {
            try
            {
                this.GridEventsRemove();
                this.MainStack.Children.Clear();
                if (_listItems is ObservableCollection<M_BasketItem> lstItems && lstItems.Count > 0)
                {
                    foreach (var aItem in lstItems)
                    {
                        var newItemObject = new MiniBasketItem();
                        newItemObject.ItemData = aItem;
                        newItemObject.DisplayLanguage = this.DisplayLanguage;
                        newItemObject.Name = string.Format("ItemStack{0}", aItem.Index);
                        this.ReregisterName(newItemObject.Name, newItemObject);
                        this.MainStack.Children.Add(newItemObject);
                    }
                    this.UpdateLayout();
                    CommonFunction.ReregisterName(this.Parent as FrameworkElement, this.Name, this);
                   
                    this.GridEventsSet();
                }

            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "ItemsButtonCreate()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        /// <summary>
        /// Events Set
        /// </summary>
        public void GridEventsSet()
        {
            try
            {
                MainGrid.PreviewMouseDown += Grid_PreviewMouseDown;
                MainGrid.PreviewMouseUp += Grid_PreviewMouseUp;
                MainGrid.PreviewMouseMove += MainGrid_PreviewMouseMove;
                MainGrid.MouseLeave += MainGrid_MouseLeave;
                foreach (var aItem in this.MainStack.Children)
                {
                    if (aItem is MiniBasketItem ItemContent)
                    {
                        ItemContent.MouseClicked += ItemContent_MouseClicked;
                    }
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "GridEventsSet()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }



        /// <summary>
        /// Events Remove
        /// </summary>
        public void GridEventsRemove()
        {
            try
            {
                MainGrid.PreviewMouseDown -= Grid_PreviewMouseDown;
                MainGrid.PreviewMouseUp -= Grid_PreviewMouseUp;
                MainGrid.PreviewMouseMove -= MainGrid_PreviewMouseMove;
                MainGrid.MouseLeave -= MainGrid_MouseLeave;
                foreach (var aItem in this.MainStack.Children)
                {
                    if (aItem is MiniBasketItem ItemContent)
                    {
                        ItemContent.MouseClicked -= ItemContent_MouseClicked;
                    }
                }
                this.MainStack.Children.Clear();
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "GridEventsRemove()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }

        #endregion Methods

        #region [ Event Handlers ]
        private void MiniBasketItems_Unloaded(object sender, RoutedEventArgs e)
        {
            this.MainStack.Children.Clear();
            this.ListItems = null;
        }
        private static void OnDisplayLanguageProperyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                if (e.NewValue is SupportLanguageType newValue && !e.NewValue.Equals(e.OldValue))
                {
                    var target = d as MiniBasketItems;
                    foreach (var aItem in target.MainStack.Children)
                    {
                        if (aItem is MiniBasketItem ItemContent)
                        {
                            ItemContent.DisplayLanguage = newValue; 
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(d, "OnDisplayLanguageProperyChanged()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }

        private static void OnVerticalOffsetPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != e.OldValue)
            {
                var target = d as MiniBasketItems;
                target.MainScroll.ScrollToVerticalOffset((double)e.NewValue);
            }
        }

        private static void OnListItemsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var target = d as MiniBasketItems;
            int oldCount = e.OldValue is ObservableCollection<M_BasketItem> oldValue ? oldValue.Count : 0;
            int newCount = e.NewValue is ObservableCollection<M_BasketItem> newValue ? newValue.Count : 0;
            if (target.VerticalOffset > 0) target.VerticalOffset = 0;
            target.ItemsButtonCreate(e.NewValue);
            if (newCount > oldCount )
            {
                if (newCount.Equals(oldCount + 1))
                {
                    target.FlipItem(target.MainStack.Children[0] as FrameworkElement);
                }
                else
                {
                    target.FlipItem(target.MainStack as FrameworkElement);
                }
            }
        }


        private void Grid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            var requstGrid = sender as Grid;
            mouseDownYposition = e.GetPosition(sender as Grid).Y;
            MoseDown = true;
        }
        private void MainGrid_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (!MoseDown) return;
            var requstGrid = sender as Grid;
            var curMouseYposition = e.GetPosition(requstGrid).Y;
            VerticalOffset = VerticalOffset + (mouseDownYposition - curMouseYposition) * 2;
            mouseDownYposition = curMouseYposition;

        }

        private void Grid_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            MoseDown = false;
        }
        private void MainGrid_MouseLeave(object sender, MouseEventArgs e)
        {
            MoseDown = false;
        }

        private void ItemContent_MouseClicked(object sender, RoutedEventArgs e)
        {
            RaiseMouseClickedEvent(e.OriginalSource);
        }

        #endregion Event Handlers
    }
}
