using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
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 ModSync
{
  /// <summary>
  /// Interaktionslogik für MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();
      DataContext = this;
      if (File.Exists(@"login.cfg")) ShowUploaad = true;
    }

    private string m_Error = "Ready";

    public string Error
    {
      get { return m_Error; }
      set
      {
        m_Error = value;
        OnPropertyChanged();
      }
    }

    private bool m_ShowUploaad;

    public bool ShowUploaad
    {
      get { return m_ShowUploaad; }
      set
      {
        m_ShowUploaad = value;
        OnPropertyChanged();
      }
    }

    private bool m_Acting = true;

    public bool Acting
    {
      get { return m_Acting; }
      set
      {
        m_Acting = value;
        OnPropertyChanged();
      }
    }

    private void Button_ClickUpload(object sender, RoutedEventArgs e)
    {
      Task.Run(new Action(() =>
      {
        Acting = false;
        try
        {
          Upload();
        }
        catch { }
        Acting = true;
      }));
    }

    private void Button_ClickDownload(object sender, RoutedEventArgs e)
    {
      Task.Run(new Action(() =>
      {
        Acting = false;
        try
        {
          Download();
        }
        catch { }
        Acting = true;
      }));
    }


    private void Upload()
    {
      Error = "...";
      string sftpHost;
      string sftpUser;
      string sftpPwd;
      int sftpPort = 22;
      try
      {

        Dictionary<string, string> dict = new Dictionary<string, string>();

        System.IO.StreamReader file = null;
        try
        {
          string line;

          file = new System.IO.StreamReader(@"login.cfg");

          while ((line = file.ReadLine()) != null)
          {
            string[] pa = line.Split("=".ToCharArray(), 2);
            if (pa.Length == 2)
            {
              dict.Add(pa[0], pa[1]);
            }
          }
        }
        finally
        {
          if (file != null)
            file.Close();
        }

        sftpHost = dict["host"];
        sftpUser = dict["user"];
        sftpPwd = dict["pw"];
        sftpPort = int.Parse(dict["port"]);
      }
      catch
      {
        Error = "Error loading login.cfg";
        return;
      }

      try
      {

        if (!Directory.Exists(@"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Temp"))
          Directory.CreateDirectory(@"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Temp");
      }
      catch
      {
        Error = "Error creating temp dir";
        return;
      }

      try
      {
        System.IO.DirectoryInfo di = new DirectoryInfo(@"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Temp");

        foreach (FileInfo file in di.GetFiles())
        {
          file.Delete();
        }
      }
      catch
      {
        Error = "Error deleting files";
        return;
      }

      try
      {
        ZipFile.CreateFromDirectory(@"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Mods", @"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Temp\mods.zip");
      }
      catch
      {
        Error = "Error creating zip";
        return;
      }


      string fileToUpload = @"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Temp\mods.zip";
      string uploadPath = "/var/www/html_files/roguelands";

      try
      {
        using (var client = new SftpClient(sftpHost, sftpPort, sftpUser, sftpPwd))
        {
          client.Connect();
          if (client.IsConnected)
          {
            client.ChangeDirectory(uploadPath);

            using (var fileStream = new FileStream(fileToUpload, FileMode.Open))
            {
              client.BufferSize = 4 * 1024; // bypass Payload error large files
              client.UploadFile(fileStream, System.IO.Path.GetFileName(fileToUpload));
            }
          }
          client.Disconnect();
        }
      }
      catch (Exception Ex)
      {
        Error = "Error uploading zip: " + Ex.Message;
        return;
      }
      Error = "Fin";
    }


    private void Download()
    {
      Error = "...";
      try
      {
        System.IO.DirectoryInfo di = new DirectoryInfo(@"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Mods");

        foreach (FileInfo file in di.GetFiles())
        {
          file.Delete();
        }
      }
      catch
      {
        Error = "Error deleting files";
        return;
      }

      try
      {

        if (!Directory.Exists(@"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Temp"))
          Directory.CreateDirectory(@"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Temp");
      }
      catch
      {
        Error = "Error creating temp dir";
        return;
      }

      try
      {
        System.IO.DirectoryInfo di = new DirectoryInfo(@"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Temp");

        foreach (FileInfo file in di.GetFiles())
        {
          file.Delete();
        }
      }
      catch
      {
        Error = "Error deleting files II";
        return;
      }

      try
      {
        using (var client = new WebClient())
        {
          client.DownloadFile("https://files.zariteis.de/roguelands/mods.zip", @"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Temp\mods.zip");
        }
      }
      catch
      {
        Error = "Error downloding files";
        return;
      }

      try
      {
        ZipFile.ExtractToDirectory(@"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Temp\mods.zip", @"C:\Program Files (x86)\Steam\steamapps\common\Roguelands\GadgetCore\Mods");
      }
      catch
      {
        Error = "Error installing files";
        return;
      }
      Error = "Fin";
    }
  }
}
