using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using PPScanControl;

namespace WPF_ScanControl_Sample
{
    /// <summary>
    /// MainWindow.xaml 的互動邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        private ScannerType scannerType;
        private ScanControl scanControl;
        private string outputDirctory;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            scanControl = new ScanControl();
            scanControl.ScanCompleted += ScanControl_ScanCompleted;
            lbApiVersion.Content = scanControl.GetApiVersion();

            // auto detect at app open
            GetScanners();
            
            // create output directory
            outputDirctory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + @"\PPScanner\";
            lbOutputPath.Content = outputDirctory;
            if (!Directory.Exists(outputDirctory))
            {
                try
                {
                    Directory.CreateDirectory(outputDirctory);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, Properties.Resources.MsgCreateTempFailed + ex.Message, null, MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }

        private void GetScanners()
        {
            scannerType = scanControl.GetConnectedScanner();
            lbCurrentScanner.Content = scannerType;
            if (scannerType == ScannerType.None)
            {
                lbCurrentScanner.Foreground = Brushes.Red;
                SetButtonEnable(false);
            }
            else
            {
                lbCurrentScanner.Foreground = Brushes.Green;
                btnOpen.IsEnabled = true;
            }
        }

        private void BtnGetScanners_OnClick(object sender, RoutedEventArgs e)
        {
            if (scanControl == null)
                scanControl = new ScanControl();
            GetScanners();
            if (scannerType == ScannerType.None)
            {
                MessageBox.Show(this, Properties.Resources.MsgNoScanner, "", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show(this, Properties.Resources.MsgCurrentScanner + scannerType, "", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void BtnOpen_OnClick(object sender, RoutedEventArgs e)
        {
            ReturnCode code = scanControl.Open(scannerType);
            if (code != ReturnCode.Success)
            {
                ShowErrorMessage(this, code);
                SetButtonEnable(false);
                if (code == ReturnCode.ScannerNotFound)
                {
                    lbOpenStatus.Content = "Closed";
                    lbOpenStatus.Foreground = Brushes.Black;
                }
                else
                {
                    lbOpenStatus.Content = "Error";
                    lbOpenStatus.Foreground = Brushes.Red;
                    btnOpen.IsEnabled = true;
                }
            }
            else
            {
                SetButtonEnable(true);
                btnOpen.IsEnabled = false;
            }
        }

        private void BtnNeedCalibrate_OnClick(object sender, RoutedEventArgs e)
        {
            ReturnCode code = scanControl.IsCalibrateNeeded();
            if (code == ReturnCode.Success)
                MessageBox.Show(this, Properties.Resources.MsgNoNeedCalibrate, "", MessageBoxButton.OK, MessageBoxImage.Information);
            else
                ShowErrorMessage(this, code);
        }

        private void BtnCalibrate_OnClick(object sender, RoutedEventArgs e)
        {
            A6_CalibrateWizard wizard = new A6_CalibrateWizard(scanControl);
            wizard.Owner = this;
            wizard.ShowDialog();
        }

        private void BtnStartScan_OnClick(object sender, RoutedEventArgs e)
        {
            string outputFileName = outputDirctory + "A6_" + DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture) + ".png";
            ReturnCode code = scanControl.StartScan(400, ImageType.PNG, outputFileName);
            if (code != ReturnCode.Success)
            {
                ShowErrorMessage(this, code);
            }
            else
            {
                lbOpenStatus.Content = "Scanning";
                lbOpenStatus.Foreground = Brushes.Red;
            }
        }

        private void ScanControl_ScanCompleted(object sender, ScanCompletedEventArgs e)
        {
            if (e.Result == ReturnCode.Success)
            {
                using (FileStream fileStream = new FileStream(e.FileName, FileMode.Open))
                {
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.StreamSource = fileStream;
                    bitmapImage.EndInit();
                    bitmapImage.Freeze();
                    imagePreview.Source = bitmapImage;
                    fileStream.Close();
                }
                MessageBox.Show(this, Properties.Resources.MsgScanReturnSuccess + e.FileName, "", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                ShowErrorMessage(this, e.Result, Properties.Resources.MsgScanReturnError);
            }

            lbOpenStatus.Content = "Opened";
            lbOpenStatus.Foreground = Brushes.Green;
        }

        private void BtnClose_OnClick(object sender, RoutedEventArgs e)
        {
            scanControl.ScanCompleted -= ScanControl_ScanCompleted;
            scanControl.Close();
            scanControl = null;
            scannerType = ScannerType.None;
            lbCurrentScanner.Content = scannerType;
            SetButtonEnable(false);

            // auto detect again
            scanControl = new ScanControl();
            scanControl.ScanCompleted += ScanControl_ScanCompleted;
            GetScanners();
        }

        private void SetButtonEnable(bool isEnabled)
        {
            btnOpen.IsEnabled = isEnabled;
            btnNeedCalibrate.IsEnabled = isEnabled;
            btnCalibrate.IsEnabled = isEnabled;
            btnStartScan.IsEnabled = isEnabled;
            btnClose.IsEnabled = isEnabled;
            if (!isEnabled)
            {
                lbOpenStatus.Content = "Closed";
                lbOpenStatus.Foreground = Brushes.Black;
            }
            else
            {
                lbOpenStatus.Content = "Opened";
                lbOpenStatus.Foreground = Brushes.Green;
            }
        }

        private void BtnOpenFolder_OnClick(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(outputDirctory))
            {
                try
                {
                    Process.Start(outputDirctory);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Failed to open directory: " + ex.Message, null, MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }

        public static void ShowErrorMessage(Window owner, ReturnCode returnCode, string appendText = null)
        {
            string msg = appendText;
            MessageBoxImage image = MessageBoxImage.Warning;
            switch (returnCode)
            {
                case ReturnCode.Success:
                    msg += Properties.Resources.MsgApiSuccess;
                    image = MessageBoxImage.Information;
                    break;
                case ReturnCode.ScannerNotFound:
                    msg += Properties.Resources.MsgNoScanner + returnCode + " (" + (int)returnCode + ")";
                    break;
                case ReturnCode.NoPaper:
                    msg += Properties.Resources.MsgNoPaper + returnCode + " (" + (int)returnCode + ")";
                    break;
                case ReturnCode.NeedCalibrate:
                    msg += Properties.Resources.MsgNeedCalibrate + " (" + (int)returnCode + ")";
                    break;
                default:
                    msg += Properties.Resources.MsgApiError + returnCode + " (" + (int)returnCode + ")";
                    break;
            }
            MessageBox.Show(owner, msg, "", MessageBoxButton.OK, image);
        }

        private void MainWindow_OnClosing(object sender, CancelEventArgs e)
        {
            if (scanControl != null)
            {
                scanControl.Close();
                scanControl = null;
            }
        }
    }
}
