using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows.Threading;
using System.Reflection;
using SPC.Kiosk.Base;
using SPC.Kiosk.Common;
using SPC.Kiosk.Popup.Model;
using SPC.Kiosk.Payments;
using System.Windows;
using System.Threading.Tasks;
using System.Threading;
using SPC.Kiosk.DataHelper;

namespace SPC.Kiosk.Popup.ViewModel
{
    /// <summary>
    /// MobileCompanyMemberCertify.xaml 의 ViewModel
    /// </summary>
    public class VmMobileHappyCoupon : PopupViewModelBase
    {
        #region [ Members ]
        private enum ProcessingType
        {
            Search,
            Using
        }
        private M_MobileCouponReturn mobileCouponReturn = new M_MobileCouponReturn();

        public M_MobileCouponReturn MobileCouponReturn
        {
            get { return mobileCouponReturn; }
            set { mobileCouponReturn = value; PropertyChange("MobileCouponReturn"); }
        }

        private List<M_BasketItem> basketData;
        /// <summary>
        /// 장바구니 상품정보
        /// </summary>
        public List<M_BasketItem> BasketData
        {
            get { return basketData; }
            set { basketData = value; PropertyChange("BasketData"); }
        }
        private double payments;
        /// <summary>
        /// Total Payments
        /// </summary>
        public double Payments
        {
            get { return payments; }
            set { payments = value; PropertyChange("Payments"); }
        }
        private double totalCouponAmount;
        /// <summary>
        /// Total Payments
        /// </summary>
        public double TotalCouponAmount
        {
            get { return totalCouponAmount; }
            set { totalCouponAmount = value; PropertyChange("TotalCouponAmount"); }
        }
        private List<M_Language> headerText;
        /// <summary>
        /// Top Header Text
        /// </summary>
        public List<M_Language> HeaderText
        {
            get { return headerText; }
            set { headerText = value; PropertyChange("HeaderText"); }
        }
        private List<M_Language> scanGuidText;
        /// <summary>
        /// Second Sub Header Text
        /// </summary>
        public List<M_Language> ScanGuidText
        {
            get { return scanGuidText; }
            set { scanGuidText = value; PropertyChange("ScanGuidText"); }
        }
        private List<M_Language> processingGuide;
        /// <summary>
        /// Processing Guide Text
        /// </summary>
        public List<M_Language> ProcessingGuide
        {
            get { return processingGuide; }
            set { processingGuide = value; PropertyChange("ProcessingGuide"); }
        }
        private List<M_Language> errorGuide;
        /// <summary>
        /// Error Guide Text
        /// </summary>
        public List<M_Language> ErrorGuide
        {
            get { return errorGuide; }
            set { errorGuide = value; PropertyChange("ErrorGuide"); }
        }

        private List<M_Language> infoGuid1Text;
        /// <summary>
        /// Bootom first infomation text
        /// </summary>
        public List<M_Language> InfoGuid1Text
        {
            get { return infoGuid1Text; }
            set { infoGuid1Text = value; PropertyChange("InfoGuid1Text"); }
        }
        private List<M_Language> infoGuid2Text;
        /// <summary>
        /// Bottom second infomation text
        /// </summary>
        public List<M_Language> InfoGuid2Text
        {
            get { return infoGuid2Text; }
            set { infoGuid2Text = value; PropertyChange("InfoGuid2Text"); }
        }
        public bool couponStartVisible = false;
        /// <summary>
        /// 시작 화면 Visible
        /// </summary>
        public bool CouponStartVisible
        {
            get { return couponStartVisible; }
            set { couponStartVisible = value; PropertyChange("CouponStartVisible"); }
        }
        public bool processingVisible = false;
        /// <summary>
        /// 진행 화면 Visible
        /// </summary>
        public bool ProcessingVisible
        {
            get { return processingVisible; }
            set { processingVisible = value; PropertyChange("ProcessingVisible"); }
        }
        public bool processingErrorVisible = false;
        /// <summary>
        /// 오류 화면 Visible
        /// </summary>
        public bool ProcessingErrorVisible
        {
            get { return processingErrorVisible; }
            set { processingErrorVisible = value; PropertyChange("ProcessingErrorVisible"); }
        }
        public bool couponUsingVisible = false;
        /// <summary>
        /// 쿠폰 목록 화면 Visible
        /// </summary>
        public bool CouponUsingVisible
        {
            get { return couponUsingVisible; }
            set { couponUsingVisible = value; PropertyChange("CouponUsingVisible"); }
        }
        public bool couponSuccessVisible = false;
        /// <summary>
        /// 쿠폰 처리 성공 Visible
        /// </summary>
        public bool CouponSuccessVisible
        {
            get { return couponSuccessVisible; }
            set { couponSuccessVisible = value; PropertyChange("CouponSuccessVisible"); }
        }
        private List<M_Language> processingMessageText;
        /// <summary>
        /// Processing Message Text
        /// </summary>
        public List<M_Language> ProcessingMessageText
        {
            get { return processingMessageText; }
            set { processingMessageText = value; PropertyChange("ProcessingMessageText"); }
        }
        private string titileImage;
        /// <summary>
        /// Titile Image
        /// </summary>
        public string TitileImage
        {
            get { return titileImage; }
            set { titileImage = value; PropertyChange("TitileImage"); }
        }
        private string processingGIF;
        /// <summary>
        /// Processing GIF
        /// </summary>
        public string ProcessingGIF
        {
            get { return processingGIF; }
            set { processingGIF = value; PropertyChange("ProcessingGIF"); }
        }
        private string errorImage;
        /// <summary>
        /// Error Icon
        /// </summary>
        public string ErrorImage
        {
            get { return errorImage; }
            set { errorImage = value; PropertyChange("ErrorImage"); }
        }
        private string successImage;
        /// <summary>
        /// Sucess Icon
        /// </summary>
        public string SuccessImage
        {
            get { return successImage; }
            set { successImage = value; PropertyChange("SuccessImage"); }
        }
        private string wonIconImage;
        /// <summary>
        /// WonIconImage
        /// </summary>
        public string WonIconImage
        {
            get { return wonIconImage; }
            set { wonIconImage = value; PropertyChange("WonIconImage"); }
        }
        private List<M_Language> errorText;
        /// <summary>
        /// Process Error Text
        /// </summary>
        public List<M_Language> ErrorText
        {
            get { return errorText; }
            set { errorText = value; PropertyChange("ErrorText"); }
        }
        private bool isErrorBlink = false;
        /// <summary>
        /// Is Error Text Blink
        /// </summary>
        public bool IsErrorBlink
        {
            get { return isErrorBlink; }
            set { isErrorBlink = value; PropertyChange("IsErrorBlink"); }
        }
        private string formatedBarCode;
        /// <summary>
        /// Read Barcode Formated Text
        /// </summary>
        public string FormatedBarCode
        {
            get { return formatedBarCode; }
            set { formatedBarCode = value; PropertyChange("FormatedBarCode"); }
        }
        private string readBarCode;
        /// <summary>
        /// Read Barcode
        /// </summary>
        public string ReadBarCode
        {
            get { return readBarCode; }
            set { readBarCode = value; PropertyChange("ReadBarCode"); }
        }
        private double discountValue = 0d;
        /// <summary>
        /// Number Pad Input Number
        /// </summary>
        public double DiscountValue
        {
            get { return discountValue; }
            set { discountValue = value; PropertyChange("DiscountValue"); }
        }
        private double cancelButtonWidth = 650d;
        /// <summary>
        /// Cancel Button Width
        /// </summary>
        public double CancelButtonWidth
        {
            get { return cancelButtonWidth; }
            set { cancelButtonWidth = value; PropertyChange("CancelButtonWidth"); }
        }
        private List<M_Language> cancelButtonText;
        /// <summary>
        /// Cancel Button Text
        /// </summary>
        public List<M_Language> CancelButtonText
        {
            get { return cancelButtonText; }
            set { cancelButtonText = value; PropertyChange("CancelButtonText"); }
        }
        private List<M_Language> okButtonText;
        /// <summary>
        /// Ok Button Text
        /// </summary>
        public List<M_Language> OkButtonText
        {
            get { return okButtonText; }
            set { okButtonText = value; PropertyChange("OkButtonText"); }
        }
        public bool oKButtonEnabled = false;
        /// <summary>
        /// OK Button enabled
        /// </summary>
        public bool OKButtonEnabled
        {
            get { return oKButtonEnabled; }
            set { oKButtonEnabled = value; PropertyChange("OKButtonEnabled"); }
        }
        private double okButtonWidth = 650d;
        /// <summary>
        /// OK Button Width
        /// </summary>
        public double OKButtonWidth
        {
            get { return okButtonWidth; }
            set { okButtonWidth = value; PropertyChange("OKButtonWidth"); }
        }

        private List<M_Language> successText;
        /// <summary>
        /// Cancel Button Text
        /// </summary>
        public List<M_Language> SuccessText
        {
            get { return successText; }
            set { successText = value; PropertyChange("SuccessText"); }
        }

        private MobileCouponWindowType couponWindow = MobileCouponWindowType.CouponStart;
        /// <summary>
        /// Current  View Window
        /// </summary>
        public MobileCouponWindowType CouponWindow
        {
            get { return couponWindow; }
            set { couponWindow = value; PropertyChange("CouponWindow"); }
        }
        private double popupWidth = 1300;
        /// <summary>
        /// Popup Whidth (For Calculate OK Button Width)
        /// </summary>
        public double PopupWidth
        {
            get { return popupWidth; }
            set { popupWidth = value; PropertyChange("PopupWidth"); }
        }
        /// <summary>
        /// OK Click Command
        /// </summary>
        public ICommand OkCommand { get; protected set; }
        /// <summary>
        /// Cancel Click Command
        /// </summary>
        public ICommand CancelCommand { get; protected set; }

        private bool ProcessStart = false;
        private posMobileHappyCoupon posMobileCoupon = null;
        private Task ProcessTask = null;
        private string certifyKey = string.Empty;
        private ProcessingType processingType = ProcessingType.Search;
        #endregion

        #region [ Ctor ]
        /// <summary>
        /// Ctor
        /// </summary>
        public VmMobileHappyCoupon()
        {
            OkCommand = new Command(OkCommandHandler);
            CancelCommand = new Command(CancelCommandHandler);
            this.PropertyChanged += VmMobileHappyCoupon_PropertyChanged;
            TitileImage = ResourceManager.GetNximagePathAdd("img_gif_barcode.gif", CommonValue.PBdesignImagesPath);
            ProcessingGIF = ResourceManager.GetNximagePathAdd("ic_alert_ing2.gif", CommonValue.PBdesignImagesPath);
            ErrorImage = ResourceManager.GetNximagePathAdd("ic_alert_error.png", CommonValue.PBdesignImagesPath);
            SuccessImage = ResourceManager.GetNximagePathAdd("ic_alert_check.png", CommonValue.PBdesignImagesPath);
            WonIconImage = ResourceManager.GetNximagePathAdd("ic_won.png", CommonValue.PBdesignImagesPath);
            HeaderText = Languages.GetMessages("LBL0047");
            ScanGuidText = Languages.GetMessages("LBL0051");
            ProcessingMessageText = Languages.GetMessages("LBL0087");
            ProcessingGuide = Languages.GetMessages("LBL0017");
            ErrorGuide = Languages.GetMessages("LBL0028");
            ErrorText = new List<M_Language>();
            OkButtonText = Languages.GetMessages("BTN0024");
            CancelButtonText = Languages.GetMessages("BTN0033");
            posMobileCoupon = new posMobileHappyCoupon();
            posMobileCoupon.ReadStart += posMobileCoupon_ReadStart;
            posMobileCoupon.ReadEnd += posMobileCoupon_ReadEnd;
            posMobileCoupon.ErrorEvent += posMobileCoupon_ErrorEvent;
            posMobileCoupon.ErrorMessageEvent += posMobileCoupon_ErrorMessageEvent;
            CouponWindow = MobileCouponWindowType.CouponStart;
        }


        ~VmMobileHappyCoupon()
        {
            this.PropertyChanged -= VmMobileHappyCoupon_PropertyChanged;
            if (ProcessTask != null)
            {
                ProcessTask.Wait();
                ProcessTask = null;
            }
            if (posMobileCoupon != null)
            {
                posMobileCoupon.ReadStart -= posMobileCoupon_ReadStart;
                posMobileCoupon.ReadEnd -= posMobileCoupon_ReadEnd;
                posMobileCoupon.ErrorEvent -= posMobileCoupon_ErrorEvent;
                posMobileCoupon.ErrorMessageEvent -= posMobileCoupon_ErrorMessageEvent;
                posMobileCoupon.Dispose();
                posMobileCoupon = null;
            }
        }

        #endregion Ctor

        #region [  Methods  ]
        private void InitError()
        {
            LastAccessTime = DateTime.Now;
            ErrorText = new List<M_Language>();
            IsErrorBlink = false;
        }
        private void MobileCouponCreateEvents()
        {
            if (posMobileCoupon != null)
            {
                posMobileCoupon.ReadStart += posMobileCoupon_ReadStart;
                posMobileCoupon.ReadEnd += posMobileCoupon_ReadEnd;
                posMobileCoupon.ErrorEvent += posMobileCoupon_ErrorEvent;
                posMobileCoupon.ErrorMessageEvent += posMobileCoupon_ErrorMessageEvent;
            }
        }
        private void MobileCouponRemoveEvents()
        {
            if (posMobileCoupon != null)
            {
                posMobileCoupon.ReadStart -= posMobileCoupon_ReadStart;
                posMobileCoupon.ReadEnd -= posMobileCoupon_ReadEnd;
                posMobileCoupon.ErrorEvent -= posMobileCoupon_ErrorEvent;
                posMobileCoupon.ErrorMessageEvent -= posMobileCoupon_ErrorMessageEvent;
            }
        }
        private void DoCouponSearch()
        {
            if (posMobileCoupon != null)
            {
                MobileCouponCreateEvents();
                var processTask = new Task(() => posMobileCoupon.StartCertifyProcessing(certifyKey, Payments));
                processTask.Start();
                processTask.Wait();
                MobileCouponRemoveEvents();
                if (posMobileCoupon.ProcessOK)
                {
                    CouponWindow = MobileCouponWindowType.CouponUsing;
                }
                else
                {
                    CouponWindow = MobileCouponWindowType.ProcessingError;
                }
                processTask = null;
            }
            TimerEnabled = true;
            ProcessStart = false;

        }
        private void DoCouponUsing()
        {
            if (posMobileCoupon != null)
            {
                MobileCouponCreateEvents();
                var processTask = new Task(() => posMobileCoupon.StartPaymentProcessing(MobileCouponReturn,Payments));
                processTask.Start();
                processTask.Wait();
                MobileCouponRemoveEvents();
                if (posMobileCoupon.ProcessOK)
                {
                    CouponWindow = MobileCouponWindowType.CouponSuccess;
                }
                else
                {
                    CouponWindow = MobileCouponWindowType.ProcessingError;
                }
                processTask = null;
            }
            TimerEnabled = true;
            ProcessStart = false;
        }
        private void DoBarCodeCouponStart()
        {
            certifyKey = ReadBarCode;
            processingType = ProcessingType.Search;
            CouponWindow = MobileCouponWindowType.Processing;
        }
        private void SetTatalUsingAmount()
        {
            if (MobileCouponReturn is M_MobileCouponReturn
                && MobileCouponReturn.VirtureCoupons.Count > 0)
            {
                TotalCouponAmount = double.Parse(MobileCouponReturn.VirtureCoupons.Sum(r => r.DiscountPrice).ToString());
            }
            else
            {
                TotalCouponAmount = 0;
            }
            
        }


        #endregion Methods

        #region [ Event Handlers ]

        private void posMobileCoupon_ErrorMessageEvent(string _errorString)
        {
            ErrorText = new List<M_Language>
            {
                new M_Language
                {
                    Type = SupportLanguageType.ko,
                    LanguageData = _errorString.Replace("\n"," ").Replace("\r","")
                },
            };
            IsErrorBlink = true;
        }

        private void posMobileCoupon_ErrorEvent(posMobileHappyCoupon.ErrorCode _errorCode)
        {
            //TODO: 공통에 에러 메세지 등록 필요
            //ErrorText = Languages.GetMessages(_errorCode.ToString());

            ErrorText = new List<M_Language>
            {
                new M_Language
                {
                    Type = SupportLanguageType.ko,
                    LanguageData = _errorCode.ToString()
                },
            };
            IsErrorBlink = true;
        }

        private void posMobileCoupon_ReadStart(object sender)
        {
            ProcessStart = true;
            TimerEnabled = false;
        }

        private void posMobileCoupon_ReadEnd(object sender)
        {
            if (sender is posMobileHappyCoupon getMobileHappyCoupon)
            {
                if (getMobileHappyCoupon.ProcessOK)
                {
                    if (processingType.Equals(ProcessingType.Search))
                    {
                        MobileCouponReturn = getMobileHappyCoupon.CouponData;
                    }
                    else if (processingType.Equals(ProcessingType.Using))
                    {
                        ReturnValue = new M_PopupReturn
                        {
                            OKAnswer = true,
                            TimeOut = false,
                            ReturnLanguage = ShowLanguageType,
                            PopupArgs = MobileCouponReturn
                        };
                    }
                }
            }

        }
        private void CancelCommandHandler(object obj)
        {
            TimerEnabled = false;
            ReturnValue = new M_PopupReturn
            {
                OKAnswer = false,
                TimeOut = false,
                ReturnLanguage = ShowLanguageType,
                PopupArgs = null
            };
            CanWindowClose = true;
        }

        private void OkCommandHandler(object obj)
        {
            switch (CouponWindow)
            {
                case MobileCouponWindowType.ProcessingError:
                    switch (processingType)
                    {
                        case ProcessingType.Search:
                            CouponWindow = MobileCouponWindowType.CouponStart;
                            break;
                        case ProcessingType.Using:
                            CouponWindow = MobileCouponWindowType.CouponUsing;
                            break;
                    }
                    break;
                case MobileCouponWindowType.CouponUsing:
                    processingType = ProcessingType.Using;
                    CouponWindow = MobileCouponWindowType.Processing;
                    break;
                case MobileCouponWindowType.CouponSuccess:
                    if (ProcessTask != null) ProcessTask.Wait();
                    CanWindowClose = true;
                    break;
            }
        }
        private void VmMobileHappyCoupon_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            try
            {
                switch (e.PropertyName)
                {
                    case "IsTimeout":
                        if (IsTimeout)
                        {
                            switch (CouponWindow)
                            {
                                case MobileCouponWindowType.CouponStart:
                                case MobileCouponWindowType.CouponUsing:
                                    ReturnValue = new M_PopupReturn
                                    {
                                        OKAnswer = false,
                                        TimeOut = true,
                                        ReturnLanguage = ShowLanguageType,
                                        PopupArgs = null
                                    };
                                    break;
                            }
                            if (ProcessTask != null) ProcessTask.Wait();
                            CanWindowClose = true;
                        }
                        break;
                    case "MobileCouponReturn":
                        SetTatalUsingAmount();
                        if (MobileCouponReturn is M_MobileCouponReturn
                            && MobileCouponReturn.VirtureCoupons.Count > 0)
                        {
                            foreach (var aCouponData in MobileCouponReturn.VirtureCoupons)
                            {
                                aCouponData.PropertyChanged += ACouponData_PropertyChanged;
                            }
                        }
                        break;
                    case "TotalCouponAmount":
                        OKButtonEnabled = TotalCouponAmount > 0;
                        break;
                    case "ReadBarCode":
                        if (!ProcessStart)
                        {
                            if (ReadBarCode.Length >= 12 && ReadBarCode.Length <= 20)
                            {
                                readBarCode = ReadBarCode;
                                FormatedBarCode = readBarCode;
                                DoBarCodeCouponStart();
                            }
                            else
                            {
                                FormatedBarCode = string.Empty;
                                OKButtonEnabled = false;
                            }
                        }
                        break;
                    case "CouponWindow":
                        CouponStartVisible = false;
                        ProcessingVisible = false;
                        ProcessingErrorVisible = false;
                        CouponUsingVisible = false;
                        CouponSuccessVisible = false;
                        switch (CouponWindow)
                        {
                            case MobileCouponWindowType.CouponStart:
                                CouponStartVisible = true;
                                break;
                            case MobileCouponWindowType.Processing:
                                ProcessingVisible = true;
                                break;
                            case MobileCouponWindowType.ProcessingError:
                                ProcessingErrorVisible = true;
                                break;
                            case MobileCouponWindowType.CouponUsing:
                                CouponUsingVisible = true;
                                break;
                            case MobileCouponWindowType.CouponSuccess:
                                CouponSuccessVisible = true;
                                break;
                        }
                        break;
                    case "CouponStartVisible":
                        if (CouponStartVisible)
                        {
                            ScanGuidText = Languages.GetMessages("LBL0051");
                            InfoGuid1Text = new List<M_Language>();
                            InfoGuid2Text = Languages.GetMessages("LBL0015");
                            CancelButtonWidth = PopupWidth;
                            OKButtonWidth = 0d;
                            OKButtonEnabled = false;
                            CancelButtonText = Languages.GetMessages("BTN0033");
                            TimeOutSeconds = CommonValue.TimeOutSeconds;
                        }
                        break;
                    case "ProcessingVisible":
                        if (ProcessingVisible)
                        {
                            ScanGuidText = new List<M_Language>();
                            InfoGuid1Text = new List<M_Language>();
                            InfoGuid2Text = new List<M_Language>();
                            CancelButtonWidth = 0d;
                            OKButtonWidth = 0d;

                            if (ProcessTask != null) ProcessTask.Wait();

                            switch (processingType)
                            {
                                case ProcessingType.Search:
                                    ProcessTask = new Task(DoCouponSearch);
                                    break;
                                case ProcessingType.Using:
                                    ProcessTask = new Task(DoCouponUsing);
                                    break;
                            }
                            ProcessTask.Start();
                        }
                        break;
                    case "ProcessingErrorVisible":
                        if (ProcessingErrorVisible)
                        {
                            ScanGuidText = Languages.GetMessages("LBL0077");
                            InfoGuid1Text = new List<M_Language>();
                            InfoGuid2Text = new List<M_Language>();
                            CancelButtonWidth = PopupWidth / 2;
                            OKButtonWidth = PopupWidth / 2;
                            OKButtonEnabled = true;
                            OkButtonText = Languages.GetMessages("BTN0007");
                            CancelButtonText = Languages.GetMessages("BTN0033");
                            TimeOutSeconds = 10d;
                        }
                        break;
                    case "CouponUsingVisible":
                        if (CouponUsingVisible)
                        {
                            ScanGuidText = new List<M_Language>();
                            SuccessText = Languages.GetMessages("LBL0113");
                            InfoGuid1Text = new List<M_Language>();
                            InfoGuid2Text = Languages.GetMessages("LBL0004");
                            CancelButtonWidth = PopupWidth / 2;
                            OKButtonWidth = PopupWidth / 2;
                            OKButtonEnabled = false;
                            OkButtonText = Languages.GetMessages("BTN0039");
                            CancelButtonText = Languages.GetMessages("BTN0033");
                            TimeOutSeconds = CommonValue.TimeOutSeconds;
                        }
                        break;
                    case "CouponSuccessVisible":
                        if (CouponSuccessVisible)
                        {
                            ScanGuidText = new List<M_Language>();
                            SuccessText = Languages.GetMessages("LBL0093");
                            InfoGuid1Text = new List<M_Language>();
                            InfoGuid2Text = new List<M_Language>();
                            CancelButtonWidth = 0d;
                            OkButtonText = Languages.GetMessages("BTN0039");
                            OKButtonWidth = PopupWidth;
                            OKButtonEnabled = true;
                            TimeOutSeconds = 5d;
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "VmMobileHappyCoupon_PropertyChanged()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }


        private void ACouponData_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            LastAccessTime = DateTime.Now;
            SetTatalUsingAmount();
        }

        #endregion Event Handlers
    }
}