using LKFWSClient.WSClient;
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;

namespace LKFWSClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        WSClient.LKFClientSession _clientSession;
        LogWindow _logWindow = null;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void buttonOpenLog_Click(object sender, RoutedEventArgs e)
        {
            _logWindow = new LogWindow();
            _logWindow.Show();
            if (_clientSession != null)
                _clientSession.Logger = _logWindow;
        }

        private void comboYear_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            comboModelYear.SelectedItem = comboYear.SelectedItem;
        }

        private async void buttonConnect_Click(object sender, RoutedEventArgs e)
        {
            _clientSession = new WSClient.LKFClientSession(textUrl.Text, _logWindow);
            var success = await _clientSession.Connect();
            if (success)
            {
                labelConnectionStatus.Content = string.Format("Version = {0}, MinYear = {1}, MaxYear = {2}", _clientSession.ServerVersion, _clientSession.MinModelYear, _clientSession.MaxModelYear);
                for (var i = _clientSession.MaxModelYear; i >= _clientSession.MinModelYear; i--)
                {
                    var s = i.ToString();
                    comboModelYear.Items.Add(s);
                    comboYear.Items.Add(s);
                }
                comboModelYear.SelectedIndex = 0;
                comboYear.SelectedIndex = 0;
            }

        }

        private void writeFile (string fileName, byte[] content)
        {
            try
            {

                if (_logWindow != null)
                {
                    _logWindow.Log(string.Format("writing to file {0}", fileName));
                }

                System.IO.File.WriteAllBytes(fileName, content);

            }
            catch (Exception ex)
            {
                if (_logWindow != null)
                {
                    _logWindow.LogException(ex);
                }
            }
        }

        private async void buttonRun_Click(object sender, RoutedEventArgs e)
        {

            if (_clientSession == null)
            {
                labelStatus.Foreground = Brushes.Red;
                labelStatus.Content = "not connected";
                return;
            }

            if (string.IsNullOrWhiteSpace(textFileName.Text))
            {
                labelStatus.Foreground = Brushes.Red;
                labelStatus.Content = "filename missing";
                return;
            }

            var prepareData = new LKFWSContracts.PrepareData();
            prepareData.dataYear = int.Parse(comboYear.SelectedItem as String);
            prepareData.modelYear = int.Parse(comboModelYear.SelectedItem as String);

            labelStatus.Foreground = Brushes.Black;
            labelStatus.Content = "initiating";

            var success = await _clientSession.Prepare(prepareData);
 
            if (success)
            {
                labelStatus.Content = "sending file";
                success = await _clientSession.UploadFile(textFileName.Text);
            }
            else
            {
                labelStatus.Content = "error initiating";
                labelStatus.Foreground = Brushes.Red;
                return;
            }

            if (success)
            {
                labelStatus.Content = "computing";
                var result = await _clientSession.Compute(new LKFWSContracts.Compute());

                labelStatus.Content = "retrieving output files";
                if (chkResult.IsChecked != null && chkResult.IsChecked.Value)
                {
                    var outputFile = await _clientSession.GetResultFile();
                    var fileName = System.IO.Path.Combine(txtOutputPath.Text, "result.txt");
                    writeFile(fileName, outputFile);
                }

                if (chkError.IsChecked != null && chkError.IsChecked.Value)
                {
                    var outputFile = await _clientSession.GetErrorFile();
                    var fileName = System.IO.Path.Combine(txtOutputPath.Text, "error.txt");
                    writeFile(fileName, outputFile);

                    outputFile = await _clientSession.GetWarningFile();
                    fileName = System.IO.Path.Combine(txtOutputPath.Text, "warning.txt");
                    writeFile(fileName, outputFile);

                    outputFile = await _clientSession.GetInfoFile();
                    fileName = System.IO.Path.Combine(txtOutputPath.Text, "info.txt");
                    writeFile(fileName, outputFile);
                }
            }
            else
            {
                labelStatus.Content = "error uploading file";
                labelStatus.Foreground = Brushes.Red;
                return;
            }

            labelStatus.Content = "done";
            labelStatus.Foreground = Brushes.DarkGreen;

        }

        private void buttonSourceFileName_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.CheckFileExists = true;

            var res = openFileDialog.ShowDialog();

            if (res != null && res.Value == true)
            {
                textFileName.Text = openFileDialog.FileName;
            }
        }

        private void buttonBrowseOutput_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new Microsoft.Win32.OpenFileDialog();
            openFileDialog.CheckPathExists = true;

            var res = openFileDialog.ShowDialog();

            if (res != null && res.Value == true)
            {
                
                txtOutputPath.Text = System.IO.Path.GetDirectoryName(openFileDialog.FileName);
            }

        }
    }
}
