using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using SPC.Kiosk.Base;
using SPC.Kiosk.Common;
using SPC.Kiosk.Popup.Model;
using SPC.Kiosk.Payments;
namespace SPC.Kiosk.Popup.ViewModel
{
    /// <summary>
    /// HappyPointUsing.xaml에 대한 ViewModel
    /// </summary>
    public class VmHappyPointCoupon : PopupViewModelBase
    {
        #region [ Members ]
        private enum ProcessingType
        {
            SingleCoupon,
            CouponUsing
        }
        private ProcessingType ProcessType { get; set; } = ProcessingType.SingleCoupon;
        private List<M_HappyCoupon> happyAppCoupons = new List<M_HappyCoupon>();
        /// <summary>
        /// Happy App Coupons
        /// </summary>
        public List<M_HappyCoupon> HappyAppCoupons
        {
            get { return happyAppCoupons; }
            set { happyAppCoupons = value; PropertyChange("HappyAppCoupons"); }
        }
        private string titileImage;
        /// <summary>
        /// Barcode Scan Image
        /// </summary>
        public string TitileImage
        {
            get { return titileImage; }
            set { titileImage = value; PropertyChange("TitileImage"); }
        }

        private List<M_Language> headerText;
        /// <summary>
        /// Top Header Text (first Grid)
        /// </summary>
        public List<M_Language> HeaderText
        {
            get { return headerText; }
            set { headerText = value; PropertyChange("HeaderText"); }
        }
        private List<M_Language> scanGuidText;
        /// <summary>
        /// Second Header Text (first Grid)
        /// </summary>
        public List<M_Language> ScanGuidText
        {
            get { return scanGuidText; }
            set { scanGuidText = value; PropertyChange("ScanGuidText"); }
        }
        private List<M_Language> infoGuid1Text;
        /// <summary>
        /// Bootom first infomation text (first Grid)
        /// </summary>
        public List<M_Language> InfoGuid1Text
        {
            get { return infoGuid1Text; }
            set { infoGuid1Text = value; PropertyChange("InfoGuid1Text"); }
        }
        private List<M_Language> infoGuid2Text;
        /// <summary>
        /// Bottom second infomation text (first Grid)
        /// </summary>
        public List<M_Language> InfoGuid2Text
        {
            get { return infoGuid2Text; }
            set { infoGuid2Text = value; PropertyChange("InfoGuid2Text"); }
        }
        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"); }
        }
        public bool couponStartVisible = false;
        /// <summary>
        /// 인증 시작 화면 Visible
        /// </summary>
        public bool CouponStartVisible
        {
            get { return couponStartVisible; }
            set { couponStartVisible = value; PropertyChange("CouponStartVisible"); }
        }
        public bool couponUsingVisible = false;
        /// <summary>
        /// Point Using Window Visible
        /// </summary>
        public bool CouponUsingVisible
        {
            get { return couponUsingVisible; }
            set { couponUsingVisible = value; PropertyChange("CouponUsingVisible"); }
        }
        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 couponSuccessVisible = false;
        /// <summary>
        /// 인증 완료 화면 Visible
        /// </summary>
        public bool CouponSuccessVisible
        {
            get { return couponSuccessVisible; }
            set { couponSuccessVisible = value; PropertyChange("CouponSuccessVisible"); }
        }
        private List<M_Language> pointPadGuidText;
        /// <summary>
        /// Point Pad Input Guide Text
        /// </summary>
        public List<M_Language> PointPadGuidText
        {
            get { return pointPadGuidText; }
            set { pointPadGuidText = value; PropertyChange("PointPadGuidText"); }
        }
        private List<M_Language> totalPayHeaderText;
        /// <summary>
        /// Payments Total Header Text
        /// </summary>
        public List<M_Language> TotalPayHeaderText
        {
            get { return totalPayHeaderText; }
            set { totalPayHeaderText = value; PropertyChange("TotalPayHeaderText"); }
        }
        private List<M_Language> queryPointsHeaderText;
        /// <summary>
        /// Member Point Header Text
        /// </summary>
        public List<M_Language> QueryPointsHeaderText
        {
            get { return queryPointsHeaderText; }
            set { queryPointsHeaderText = value; PropertyChange("QueryPointsHeaderText"); }
        }

        private List<M_Language> processingMessageText;
        /// <summary>
        /// Number Pad Input Guide Text
        /// </summary>
        public List<M_Language> ProcessingMessageText
        {
            get { return processingMessageText; }
            set { processingMessageText = value; PropertyChange("ProcessingMessageText"); }
        }
        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> successText;
        /// <summary>
        /// Sucess Guide Text
        /// </summary>
        public List<M_Language> SuccessText
        {
            get { return successText; }
            set { successText = value; PropertyChange("SuccessText"); }
        }
        private double payments;
        /// <summary>
        /// Payments Total
        /// </summary>
        public double Payments
        {
            get { return payments; }
            set { payments = value; PropertyChange("Payments"); }
        }
        private List<M_Language> errorText;
        /// <summary>
        /// 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 Barcoe 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 List<M_Language> cancelButtonText;
        /// <summary>
        /// Cancel Button Text
        /// </summary>
        public List<M_Language> CancelButtonText
        {
            get { return cancelButtonText; }
            set { cancelButtonText = value; PropertyChange("CancelButtonText"); }
        }
        private double cancelButtonWidth = 270d;
        /// <summary>
        /// Cancel Button Width
        /// </summary>
        public double CancelButtonWidth
        {
            get { return cancelButtonWidth; }
            set { cancelButtonWidth = value; PropertyChange("CancelButtonWidth"); }
        }
        private double okButtonWidth = 270d;
        /// <summary>
        /// OK Button Width
        /// </summary>
        public double OKButtonWidth
        {
            get { return okButtonWidth; }
            set { okButtonWidth = value; PropertyChange("OKButtonWidth"); }
        }
        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 HappyCouponWindowType happyCouponWindow = HappyCouponWindowType.CouponStart;
        /// <summary>
        /// Current  View Window
        /// </summary>
        public HappyCouponWindowType HappyCouponWindow
        {
            get { return happyCouponWindow; }
            set { happyCouponWindow = value; PropertyChange("HappyCouponWindow"); }
        }
        private double popupWidth = 1300;
        /// <summary>
        /// Popup Whidth (For Calculate OK Button Width)
        /// </summary>
        public double PopupWidth
        {
            get { return popupWidth; }
            set { popupWidth = value; PropertyChange("PopupWidth"); }
        }
        private M_HappyPointReturn happyPointReturn;
        /// <summary>
        /// HappyPoint 인증 정보
        /// </summary>
        public M_HappyPointReturn HappyPointReturn
        {
            get { return happyPointReturn; }
            set { happyPointReturn = value; PropertyChange("HappyPointReturn"); }
        }
        /// <summary>
        /// OK Click Command
        /// </summary>
        public ICommand OkCommand { get; protected set; }
        /// <summary>
        /// Cancel Click Command
        /// </summary>
        public ICommand CancelCommand { get; protected set; }
        /// <summary>
        /// Coupon Selectd
        /// </summary>
        public ICommand CouponCommand { get; protected set; }
        private bool ProcessStart = false;
        private posHappyPoint posHappyPoint = null;
        private Task ProcessTask  = null;
        private string certifyKey = string.Empty;
        #endregion  Members

        #region [ Ctor ]
        /// <summary>
        /// Ctor
        /// </summary>
        public VmHappyPointCoupon()
        {
            OkCommand = new Command(OkCommandHandler);
            CancelCommand = new Command(CancelCommandHandler);
            CouponCommand = new Command(CouponCommandHandler);
            this.PropertyChanged += VmHappyPointCoupon_PropertyChanged;
            TitileImage = ResourceManager.GetNximagePathAdd("img_gif_barcode_happy.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);
            ErrorText = new List<M_Language>();
            OkButtonText = Languages.GetMessages("BTN0024");
            CancelButtonText = Languages.GetMessages("BTN0033");
            HeaderText = Languages.GetMessages("LBL0133");
            ProcessingMessageText = Languages.GetMessages("LBL0087");
            ProcessingGuide = Languages.GetMessages("LBL0028");
            ErrorGuide = Languages.GetMessages("LBL0028");
            posHappyPoint = new posHappyPoint();

        }

        
        public new void Dispose()
        {
            TitileImage = string.Empty; 
            ProcessingGIF = string.Empty;
            ErrorImage = string.Empty;
            this.PropertyChanged -= VmHappyPointCoupon_PropertyChanged;
            if (ProcessTask != null)
            {
                ProcessTask.Dispose();
                ProcessTask = null;
            }
            if (posHappyPoint != null)
            {
                HappyPointRemoveEvents();
                posHappyPoint.Dispose();
                posHappyPoint = null;
            }
            base.Dispose();
        }
        #endregion Ctor

        #region [ Methods ]
        private void TestDelay()
        {
            Thread.Sleep(3000);
        }
        private void HappyPointCreateEvents()
        {
            if (posHappyPoint != null)
            {
                posHappyPoint.ReadStart += PosHappyPoint_ReadStart;
                posHappyPoint.ReadEnd += PosHappyPoint_ReadEnd;
                posHappyPoint.ErrorEvent += PosHappyPoint_ErrorEvent;
                posHappyPoint.ErrorMessageEvent += PosHappyPoint_ErrorMessageEvent;
            }
        }
        private void HappyPointRemoveEvents()
        {
            if (posHappyPoint != null)
            {
                posHappyPoint.ReadStart -= PosHappyPoint_ReadStart;
                posHappyPoint.ReadEnd -= PosHappyPoint_ReadEnd;
                posHappyPoint.ErrorEvent -= PosHappyPoint_ErrorEvent;
                posHappyPoint.ErrorMessageEvent -= PosHappyPoint_ErrorMessageEvent;
            }
        }
        private void DoSingleCouponCertify()
        {

            HappyPointCreateEvents();
            var processTask = new Task(() => posHappyPoint.StartCouponProcessing(certifyKey,Payments));
            processTask.Start();
            processTask.Wait();
            HappyPointRemoveEvents();
            if (posHappyPoint.ProcessOK)
            {
                HappyCouponWindow = HappyCouponWindowType.CouponSuccess;
            }
            else
            {
                HappyCouponWindow = HappyCouponWindowType.ProcessingError;
            }
            processTask = null;
            TimerEnabled = true;
            ProcessStart = false;
        }


        #endregion Methods

        #region [ Event Handlers ]
        private void CouponCommandHandler(object obj)
        {
            if (obj is M_HappyCoupon selectCoupon)
            {
                //var newHappyAppCoupons = HappyAppCoupons;
                //var selectNumber = selectCoupon.Number;
                //var selectItem = newHappyAppCoupons.Find(r => r.Number.Equals(selectNumber));
                //if (selectCoupon.IsUsed)
                //{
                //    certifyKey = string.Empty;
                //    selectItem.IsUsed = false;
                //}
                //else
                //{
                //    if (newHappyAppCoupons.Where(r => r.IsUsed).Count().Equals(0))
                //    {
                //        certifyKey = selectItem.Number;
                //        selectItem.IsUsed = true;
                //    }
                //}
                //HappyAppCoupons = newHappyAppCoupons;
                if (selectCoupon.IsUsed) certifyKey = selectCoupon.Number;
                OKButtonEnabled = HappyAppCoupons.Where(r => r.IsUsed).Count() > 0;
            }
        }

        private void CancelCommandHandler(object obj)
        {
            TimerEnabled = false;
            ReturnValue = new M_PopupReturn
            {
                OKAnswer = false,
                TimeOut = false,
                ReturnLanguage = ShowLanguageType,
                PopupArgs = HappyPointReturn is M_HappyPointReturn && HappyPointReturn.ReservePoint
                          ? HappyPointReturn
                          : null
            };
            CanWindowClose = true;
        }
        private void OkCommandHandler(object obj)
        {
            switch (HappyCouponWindow)
            {
                case HappyCouponWindowType.CouponUsing:
                    HappyCouponWindow = HappyCouponWindowType.Processing;
                    break;
                case HappyCouponWindowType.ProcessingError:
                    switch (ProcessType)
                    {
                        case ProcessingType.SingleCoupon:
                            HappyCouponWindow = HappyCouponWindowType.CouponStart;
                            break;
                        case ProcessingType.CouponUsing:
                            HappyCouponWindow = HappyCouponWindowType.CouponUsing;
                            break;
                    }
                    break;
                case HappyCouponWindowType.CouponSuccess:
                    if (ProcessTask != null) ProcessTask.Wait();
                    CanWindowClose = true;
                    break;
            }
        }


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

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

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

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

        private void PosHappyPoint_ReadEnd(object sender)
        {
            ProcessStart = false;
            try
            {
                if (sender is posHappyPoint getPosposHappyPoint)
                {
                    if (getPosposHappyPoint.ProcessOK)
                    {
                        ReturnValue = new M_PopupReturn
                        {
                            OKAnswer = true,
                            TimeOut = false,
                            ReturnLanguage = ShowLanguageType,
                            PopupArgs = getPosposHappyPoint.UsedCoupon
                        };
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                TimerEnabled = true;
            }

        }
        private void VmHappyPointCoupon_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            try
            {
                switch (e.PropertyName)
                {
                    case "IsTimeout":
                        if (IsTimeout)
                        {
                            switch (HappyCouponWindow)
                            {
                                case HappyCouponWindowType.CouponStart:
                                case HappyCouponWindowType.CouponUsing:
                                case HappyCouponWindowType.ProcessingError:
                                    ReturnValue = new M_PopupReturn
                                    {
                                        OKAnswer = false,
                                        TimeOut = true,
                                        ReturnLanguage = ShowLanguageType,
                                        PopupArgs = null
                                    };
                                    break;
                            }
                            if (ProcessTask != null) ProcessTask.Wait();
                            CanWindowClose = true;
                        }
                        break;
                    case "HappyPointReturn":
                        if (HappyPointReturn is M_HappyPointReturn
                            && HappyPointReturn.MyHappyCoupons is List<M_HappyCoupon>)
                        {
                            HappyAppCoupons = HappyPointReturn.MyHappyCoupons;
                        }
                        break;
                    case "HappyCouponWindow":
                        CouponStartVisible = false;
                        CouponUsingVisible = false;
                        ProcessingVisible = false;
                        ProcessingErrorVisible = false;
                        CouponSuccessVisible = false;
                        switch (HappyCouponWindow)
                        {
                            case HappyCouponWindowType.CouponStart:
                                CouponStartVisible = true;
                                break;
                            case HappyCouponWindowType.CouponUsing:
                                CouponUsingVisible = true;
                                break;
                            case HappyCouponWindowType.Processing:
                                ProcessingVisible = true;
                                break;
                            case HappyCouponWindowType.ProcessingError:
                                ProcessingErrorVisible = true;
                                break;
                            case HappyCouponWindowType.CouponSuccess:
                                CouponSuccessVisible = true;
                                break;
                        }
                        break;
                    case "CouponStartVisible":
                        if (CouponStartVisible)
                        {
                            ScanGuidText = Languages.GetMessages("LBL0051");
                            InfoGuid1Text = new List<M_Language>();
                            InfoGuid2Text = new List<M_Language>();
                            ProcessType = ProcessingType.SingleCoupon;
                            CancelButtonWidth = PopupWidth;
                            OKButtonWidth = 0d;
                            OKButtonEnabled = false;
                            CancelButtonText = Languages.GetMessages("BTN0033");
                            TimeOutSeconds = CommonValue.TimeOutSeconds;
                        }
                        break;
                    case "CouponUsingVisible":
                        if (CouponUsingVisible)
                        {
                            ScanGuidText = Languages.GetMessages("LBL0062");
                            InfoGuid1Text = new List<M_Language>();
                            InfoGuid2Text = Languages.GetMessages("LBL0016");
                            ProcessType = ProcessingType.CouponUsing;
                            CancelButtonWidth = PopupWidth / 2;
                            OKButtonWidth = PopupWidth / 2;
                            OKButtonEnabled = false;
                            OkButtonText = Languages.GetMessages("BTN0024");
                            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();
                            ProcessTask = new Task(DoSingleCouponCertify);
                            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 "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;
                    case "ReadBarCode":
                        if (!ProcessStart)
                        {
                            switch (ReadBarCode.Length)
                            {
                                case 11:
                                case 12:
                                    certifyKey = ReadBarCode.Substring(0, 11);
                                    FormatedBarCode = ReadBarCode.GetEncriptCardNo();
                                    HappyCouponWindow = HappyCouponWindowType.Processing;
                                    break;

                                default:
                                    FormatedBarCode = string.Empty;
                                    OKButtonEnabled = false;
                                    break;
                            }
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                CommonLog.ErrorLogWrite(this, "VmHappyPointCoupon_PropertyChanged()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }
        #endregion Event Handlers

    }
}