using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;
using System.Diagnostics;
using System.IO;

namespace barry
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public bool autorun = false;
        internal BackupConfig bkp;

        public MainWindow()
        {
            InitializeComponent();
            displays_barry_picture();

            lbl_cpuname.Content = methods.computer_name();
            lbl_driveletter.Content = methods.current_drive_label() + " (" + methods.current_drive_letter() + ")";
            lbl_cpu_uuid.Content = methods.get_machine_guid();

            try
            {
                bkp = methods.load_this_cpu();
            }
            catch (DirectoryNotFoundException e)
            {
                bkp = null;
                MessageBox.Show("Error while loading the backup: " + e.Data);
            }

            init_console();
            if (autorun)
            {
                run_backup();
            }
        }

        internal void init_console()
        {
            txt_console.Document.Blocks.Clear();
            print("**** BARRY Backup ****");
            if (bkp == null)
            {
                print("  >> unknown machine");
                btn_backup.IsEnabled = false;
                btn_preview.IsEnabled = false;
            }
            else
            {
                print(bkp.describe());
            }
        }

        internal string bkp_source()
        {
            return bkp.source_path();
        }

        internal string bkp_target()
        {
            return bkp.target_path();
        }

        private void displays_barry_picture()
        {
            BitmapImage bitmap = new BitmapImage(new Uri(System.IO.Path.Combine(methods.current_folder(), "barry.png"), UriKind.Relative));
            img_barry.Source = bitmap;
        }

        public void print(string line, bool flush = false)
        {
            txt_console.AppendText(line + "\r");
            txt_console.ScrollToEnd();
        }

        private void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            Dispatcher.BeginInvoke(new Action(() => autoexec()), DispatcherPriority.ContextIdle, null);
        }

        private void btn_backup_Click(object sender, RoutedEventArgs e)
        {
            run_backup();
        }

        private void btn_preview_Click(object sender, RoutedEventArgs e)
        {
            preview_backup();
        }

        public void run_backup()
        {
            init_console();
            cmd(String.Format("ROBOCOPY {0} {1} /E /XO /w:1 /r:3 /NP", bkp_source(), bkp_target()));
            bkp.last_bkp_date = String.Format("{0:yyyy-mm-dd hh:mm}", DateTime.Now);
            bkp.last_bkp_result = "SUCCESS";
        }

        public void autoexec()
        {
            if (bkp != null)
            {
                if (bkp.autoexec)
                {
                    run_backup();
                }
            }
        }

        public void preview_backup()
        {
            init_console();
            cmd(String.Format("ROBOCOPY {0} {1} /E /XO /L /NJH", bkp_source(), bkp_target()));
            
        }

        public void cmd(string cmd)
        {
            using (System.Diagnostics.Process p = new System.Diagnostics.Process())
            {
                print(">> " + cmd);

                p.StartInfo.FileName = "CMD.EXE";
                p.StartInfo.Arguments = String.Format("/C {0}", cmd);

                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                //p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                //p.StartInfo.RedirectStandardInput = true;

                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.StandardErrorEncoding = Encoding.UTF8;
                p.StartInfo.CreateNoWindow = true;
                p.OutputDataReceived += new DataReceivedEventHandler(process_ouput_handler);
                //p.ErrorDataReceived += new DataReceivedEventHandler(process_error_handler);

                p.Start();
                p.BeginOutputReadLine();

            }

        }

        private void process_ouput_handler(object sendingProcess, DataReceivedEventArgs outLine)
        {
            Dispatcher.BeginInvoke(new Action(() => print(outLine.Data)), DispatcherPriority.ContextIdle, null);
        }

        private void process_error_handler(object sendingProcess, DataReceivedEventArgs outLine)
        {
            Dispatcher.BeginInvoke(new Action(() => print(outLine.Data)), DispatcherPriority.ContextIdle, null);
        }

        private void btn_configure_Click(object sender, RoutedEventArgs e)
        {
            if (bkp == null)
            {
                string msg = "Barry do not know this computer, do you want him to memorize it?";
                MessageBoxResult result = MessageBox.Show(msg, "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.No)
                {
                    return;
                }
                methods.register_this_cpu();
                bkp = methods.load_this_cpu();
            }

            Window opt_window = new OptionsWindow(bkp);
            opt_window.Owner = this;
            opt_window.ShowDialog();
            init_console();
        }
    }



}

