using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Renci.SshNet;
using Valg.EVA.Skanning.Scan.Startup.StateReporting;

namespace Valg.EVA.Skanning.Scan.Presentation.StateReporting
{

    class SftpReportSink : IReportSink
    {
        private readonly string _password;
        private readonly string _username;
        private readonly string _host;
        private readonly int _port;

        public SftpReportSink(string connectionString)
        {
            var parts = connectionString.Split(':', '@');
            if (parts.Length < 3)
            {
                throw new ArgumentException("Required format: username:password@host OR  username:password@host:port");
            }
            _username = parts[0];
            _password = parts[1];
            _host = parts[2];
            _port = parts.Length > 3 ? int.Parse(parts[3]) : 22;
        }

        public void Send(StateReport report)
        {
            var payload = JsonConvert.SerializeObject(report);
            var jsonName = Path.Combine(Path.GetTempPath(), $"{System.Guid.NewGuid()}.json");
            File.WriteAllText(jsonName, payload);
            UploadSftpFile(jsonName, "");
            File.Delete(jsonName);
        }

        private  void UploadSftpFile( string sourceFile, string destinationPath)
        {
            using (SftpClient client = new SftpClient(_host, _port, _username, _password))
            {
                client.Connect();
                client.ChangeDirectory(destinationPath);
                using (var fs = new FileStream(sourceFile, FileMode.Open))
                {
                    client.BufferSize = 4 * 1024;
                    client.UploadFile(fs, Path.GetFileName(sourceFile));
                }
            }
        }
    }
}

