using QRCoder;
using SWRIS.Core;
using SWRIS.Extensions;
using SWRIS.Models;
using System.Drawing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace SWRIS
{
    /// <summary>
    /// SoftAuthDialog.xaml 的交互逻辑
    /// </summary>
    public partial class SoftAuthDialog : Window
    {
        public SoftAuthorizeModel AuthorizeModel { get; set; }
        public SoftAuthDialog()
        {
            InitializeComponent();
            AuthorizeModel = new SoftAuthorizeModel() { MachineCode = SoftAuth.GetMachineCode() };
            DataContext = this;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (AuthorizeModel.MachineCode != null)
            {
                QRCodeGenerator qrGenerator = new QRCodeGenerator();
                QRCodeData qrCodeData = qrGenerator.CreateQrCode(AuthorizeModel.MachineCode, QRCodeGenerator.ECCLevel.Q);
                QRCode qrCode = new QRCode(qrCodeData);
                Bitmap qrCodeImage = qrCode.GetGraphic(10);
                imgQRCode.Source = qrCodeImage.ConvertBitmapToBitmapImage();
            }
        }

        private void Copy_Click(object sender, RoutedEventArgs e)
        {
            Clipboard.SetDataObject(AuthorizeModel.MachineCode);
        }

        private void PasteExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            IDataObject iData = Clipboard.GetDataObject();
            if (iData.GetDataPresent(DataFormats.Text))
            {
                var finalCode = (string)iData.GetData(DataFormats.Text);
                AuthorizeModel.FinalData.Set(finalCode);
            }
            e.Handled = true;
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = SoftAuth.WriteRegistry(AuthorizeModel.FinalCode);
        }

        private void Fourth_TextChanged(object sender, TextChangedEventArgs e)
        {
            var fourth = sender as TextBox;
            if (fourth.Text.Length == fourth.MaxLength)
            {
                if (SoftAuth.CheckFinalCode(AuthorizeModel.FinalCode))
                {
                    piCheckResult.Visibility = Visibility.Visible;
                    btnSave.IsEnabled = true;
                    return;
                }
            }
            piCheckResult.Visibility = Visibility.Hidden;
            btnSave.IsEnabled = false;
        }

        private void Card_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);
            DragMove();
        }
    }
}
