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;
namespace SPC.Kiosk.Popup.ViewModel
{
    /// <summary>
    /// MobileCompanyMemberCertify.xaml 의 ViewModel
    /// </summary>
    public class VmMobileCompanyMemberCertify : PopupViewModelBase
    {
        #region [ Members ]
        private MobileCompanyType mobileCompany;
        /// <summary>
        /// Mobile Company Type
        /// </summary>
        public MobileCompanyType MobileCompany
        {
            get { return mobileCompany; }
            set { mobileCompany = value; PropertyChange("MobileCompany"); }
        }
        private List<M_Language> mobileCompanyName;
        /// <summary>
        /// Mobile Company Name
        /// </summary>
        public List<M_Language> MobileCompanyName
        {
            get { return mobileCompanyName; }
            set { mobileCompanyName = value; PropertyChange("MobileCompanyName"); }
        }
        private double payments;
        /// <summary>
        /// Total Payments
        /// </summary>
        public double Payments
        {
            get { return payments; }
            set { payments = value; PropertyChange("Payments"); }
        }
        private List<M_Language> headerSubText;
        /// <summary>
        /// Top Sub Header Text
        /// </summary>
        public List<M_Language> HeaderSubText
        {
            get { return headerSubText; }
            set { headerSubText = value; PropertyChange("HeaderSubText"); }
        }
        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 certifyStartVisible = false;
        /// <summary>
        /// 인증 시작 화면 Visible
        /// </summary>
        public bool CertifyStartVisible
        {
            get { return certifyStartVisible; }
            set { certifyStartVisible = value; PropertyChange("CertifyStartVisible"); }
        }
        public bool certifyProcessingVisible = false;
        /// <summary>
        /// 인증 진행 화면 Visible
        /// </summary>
        public bool CertifyProcessingVisible
        {
            get { return certifyProcessingVisible; }
            set { certifyProcessingVisible = value; PropertyChange("CertifyProcessingVisible"); }
        }
        public bool processingErrorVisible = false;
        /// <summary>
        /// 인증 오류 화면 Visible
        /// </summary>
        public bool ProcessingErrorVisible
        {
            get { return processingErrorVisible; }
            set { processingErrorVisible = value; PropertyChange("ProcessingErrorVisible"); }
        }
        public bool certifySuccessVisible = false;
        /// <summary>
        /// 인증 완료 화면 Visible
        /// </summary>
        public bool CertifySuccessVisible
        {
            get { return certifySuccessVisible; }
            set { certifySuccessVisible = value; PropertyChange("CertifySuccessVisible"); }
        }
        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 string titileImage;
        /// <summary>
        /// Read Barcode Formated Text
        /// </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 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 = 150d;
        /// <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 CertifyWindowType certifyWindow = CertifyWindowType.CertifyStart;
        /// <summary>
        /// Current  View Window
        /// </summary>
        public CertifyWindowType CertifyWindow
        {
            get { return certifyWindow; }
            set { certifyWindow = value; PropertyChange("CertifyWindow"); }
        }
        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>
        /// 통신사 할인 정보
        /// </summary>
        public M_MobileCompanyReturn MobileCompanyReturnVlaue { get; set; }
        /// <summary>
        /// OK Click Command
        /// </summary>
        public ICommand OkCommand { get; protected set; }
        /// <summary>
        /// Cancel Click Command
        /// </summary>
        public ICommand CancelCommand { get; protected set; }
        private bool DiscountProcessStart = false;
        private posMobileCompanyDiscount posTelecomDiscount = null;
        private Task ProcessTask = null;
        private string certifyKey = string.Empty;
        #endregion

        #region [ Ctor ]
        /// <summary>
        /// Ctor
        /// </summary>
        public VmMobileCompanyMemberCertify()
        {
            OkCommand = new Command(OkCommandHandler);
            CancelCommand = new Command(CancelCommandHandler);
            this.PropertyChanged += VmMobileCompanyMemberCertify_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);
            HeaderSubText = new List<M_Language>
                            {
                                new M_Language
                                {
                                    Type = SupportLanguageType.ko,
                                    LanguageData = "할인"
                                },
                                new M_Language
                                {
                                    Type = SupportLanguageType.en,
                                    LanguageData = "Discount"
                                },
                            };
            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");
            posTelecomDiscount = new posMobileCompanyDiscount();
            posTelecomDiscount.ReadStart += posTelecomDiscount_ReadStart;
            posTelecomDiscount.ReadEnd += posTelecomDiscount_ReadEnd;
            posTelecomDiscount.ErrorEvent += posTelecomDiscount_ErrorEvent;
            posTelecomDiscount.ErrorMessageEvent += posTelecomDiscount_ErrorMessageEvent;
            CertifyWindow = CertifyWindowType.CertifyStart;
        }
        ~VmMobileCompanyMemberCertify()
        {
            this.PropertyChanged -= VmMobileCompanyMemberCertify_PropertyChanged;
            if (ProcessTask != null)
            {
                ProcessTask.Dispose();
                ProcessTask = null;
            }
            if (posTelecomDiscount != null)
            {
                posTelecomDiscount.ReadStart -= posTelecomDiscount_ReadStart;
                posTelecomDiscount.ReadEnd -= posTelecomDiscount_ReadEnd;
                posTelecomDiscount.ErrorEvent -= posTelecomDiscount_ErrorEvent;
                posTelecomDiscount.ErrorMessageEvent -= posTelecomDiscount_ErrorMessageEvent;
                posTelecomDiscount.Dispose();
                posTelecomDiscount = null;
            }
        }

        #endregion Ctor

        #region [  Methods  ]
        private void InitError()
        {
            LastAccessTime = DateTime.Now;
            ErrorText = new List<M_Language>();
            IsErrorBlink = false;
        }
        private void TelecomCreateEvents()
        {
            if (posTelecomDiscount != null)
            {
                posTelecomDiscount.ReadStart += posTelecomDiscount_ReadStart;
                posTelecomDiscount.ReadEnd += posTelecomDiscount_ReadEnd;
                posTelecomDiscount.ErrorEvent += posTelecomDiscount_ErrorEvent;
                posTelecomDiscount.ErrorMessageEvent += posTelecomDiscount_ErrorMessageEvent;
            }
        }
        private void TelecomRemoveEvents()
        {
            if (posTelecomDiscount != null)
            {
                posTelecomDiscount.ReadStart -= posTelecomDiscount_ReadStart;
                posTelecomDiscount.ReadEnd -= posTelecomDiscount_ReadEnd;
                posTelecomDiscount.ErrorEvent -= posTelecomDiscount_ErrorEvent;
                posTelecomDiscount.ErrorMessageEvent -= posTelecomDiscount_ErrorMessageEvent;
            }
        }
        private void DoMobileCompanyMemberCertify()
        {
            if (posTelecomDiscount != null)
            {
                TelecomCreateEvents();
                var processTask = new Task(() => posTelecomDiscount.StartCertifyProcessing(certifyKey,MobileCompany,Payments));
                processTask.Start();
                processTask.Wait();
                TelecomRemoveEvents();
                processTask = null;
            }
        }
        private void DoBarCodeMobileCompanyMemberCertify()
        {
            FormatedBarCode = ReadBarCode.GetEncriptCardNo();
            certifyKey = ReadBarCode;
            CertifyWindow = CertifyWindowType.CertifyProcessing;
        }
        #endregion Methods

        #region [ Event Handlers ]
        private void posTelecomDiscount_ErrorMessageEvent(string _errorString)
        {
            ErrorText = new List<M_Language>
            {
                new M_Language
                {
                    Type = SupportLanguageType.ko,
                    LanguageData = _errorString.Replace("\n"," ").Replace("\r","")
                },
            };
            IsErrorBlink = true;
            CertifyWindow = CertifyWindowType.ProcessingError;
        }

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

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

        private void posTelecomDiscount_ReadStart(object sender)
        {
            DiscountProcessStart = true;
            TimerEnabled = false;
        }

        private void posTelecomDiscount_ReadEnd(object sender)
        {
            if (sender is posMobileCompanyDiscount getTelecomDiscount)
            {
                if (getTelecomDiscount.ProcessOK)
                {
                    MobileCompanyReturnVlaue = new M_MobileCompanyReturn
                    {
                        Company = getTelecomDiscount.MobileCompany,
                        MemberCode = getTelecomDiscount.CertifyKey,
                        ApprovalPayments = getTelecomDiscount.Payment,
                        DiscountValue = getTelecomDiscount.DiscountValue,
                        PaySEQ = getTelecomDiscount.PaySEQ,
                    };
                    ReturnValue = new M_PopupReturn
                    {
                        OKAnswer = true,
                        TimeOut = false,
                        ReturnLanguage = ShowLanguageType,
                        PopupArgs = MobileCompanyReturnVlaue
                    };
                    DiscountValue = MobileCompanyReturnVlaue.DiscountValue;
                    CertifyWindow = CertifyWindowType.CertifySuccess;
                }
            }
            TimerEnabled = true;
            DiscountProcessStart = false;

        }
        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 (CertifyWindow)
            {
                case CertifyWindowType.ProcessingError:
                    CertifyWindow = CertifyWindowType.CertifyStart;
                    break;
                case CertifyWindowType.CertifySuccess:
                    if (ProcessTask != null) ProcessTask.Wait();
                    CanWindowClose = true;
                    break;
            }
        }
        private void VmMobileCompanyMemberCertify_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            try
            {
                switch (e.PropertyName)
                {
                    case "IsTimeout":
                        if (IsTimeout)
                        {
                            switch (CertifyWindow)
                            {
                                case CertifyWindowType.CertifyStart:
                                case CertifyWindowType.ProcessingError:
                                    ReturnValue = new M_PopupReturn
                                    {
                                        OKAnswer = false,
                                        TimeOut = true,
                                        ReturnLanguage = ShowLanguageType,
                                        PopupArgs = null
                                    };
                                    break;
                            }
                            if (ProcessTask != null) ProcessTask.Wait();
                            CanWindowClose = true;
                        }
                        break;
                    case "ReadBarCode":
                        if (!DiscountProcessStart)
                        {
                            switch (ReadBarCode.Length)
                            {
                                case 17:
                                    readBarCode = ReadBarCode.Substring(0, 16);
                                    FormatedBarCode = ReadBarCode.GetEncriptCardNo();
                                    DoBarCodeMobileCompanyMemberCertify();
                                    break;
                                case 16:
                                    FormatedBarCode = ReadBarCode.GetEncriptCardNo();
                                    DoBarCodeMobileCompanyMemberCertify();
                                    break;
                                default:
                                    FormatedBarCode = string.Empty;
                                    OKButtonEnabled = false;
                                    break;
                            }
                        }
                        break;
                    case "CertifyWindow":
                        CertifyStartVisible = false;
                        CertifyProcessingVisible = false;
                        ProcessingErrorVisible = false;
                        CertifySuccessVisible = false;
                        switch (CertifyWindow)
                        {
                            case CertifyWindowType.CertifyStart:
                                CertifyStartVisible = true;
                                break;
                            case CertifyWindowType.CertifyProcessing:
                                CertifyProcessingVisible = true;
                                break;
                            case CertifyWindowType.ProcessingError:
                                ProcessingErrorVisible = true;
                                break;
                            case CertifyWindowType.CertifySuccess:
                                CertifySuccessVisible = true;
                                break;
                        }
                        break;
                    case "MobileCompany":
                        MobileCompanyName = MobileCompany.GetMobileCompanyName();
                        break;
                    case "CertifyStartVisible":
                        if (CertifyStartVisible)
                        {
                            ScanGuidText = Languages.GetMessages("LBL0082");
                            InfoGuid1Text = new List<M_Language>();
                            InfoGuid2Text = Languages.GetMessages("LBL0003");
                            CancelButtonWidth = PopupWidth;
                            OKButtonWidth = 0d;
                            OKButtonEnabled = false;
                            CancelButtonText = Languages.GetMessages("BTN0033");
                            TimeOutSeconds = CommonValue.TimeOutSeconds;
                        }
                        break;
                    case "CertifyProcessingVisible":
                        if (CertifyProcessingVisible)
                        {
                            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(DoMobileCompanyMemberCertify);
                            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 "CertifySuccessVisible":
                        if (CertifySuccessVisible)
                        {
                            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, "VmMobileCompanyMemberCertify_PropertyChanged()", "Fail !!", string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
            }
        }

        #endregion Event Handlers
    }
}