using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Valg.EVA.Skanning.Scan.Startup.StateReporting
{
    public class FtpReportSink : IReportSink
    {
        private string _password;
        private string _username;
        private string _endpointUrl;

        public FtpReportSink(string endpointUrl, string username, string password)
        {
            _endpointUrl = endpointUrl.TrimEnd('/');
            _username = username;
            _password = password;
        }
        public FtpReportSink(string endpointUrl)
        {

                _endpointUrl = endpointUrl.TrimEnd('/');
                _username = null;
                _password = null;
            if (!endpointUrl.StartsWith("ftp://"))
            {
                return;
            }
            var urlWithoutProtocol = endpointUrl.Substring("ftp://".Length);
            if (!urlWithoutProtocol.Contains(':'))
            {
                return;
            }
            var colon = urlWithoutProtocol.IndexOf(':');
            var at = urlWithoutProtocol.IndexOf('@');
            if (at <= colon)
            {
                return;
            }

            _username = urlWithoutProtocol.Substring(0, colon);
            _password = urlWithoutProtocol.Substring(colon + 1, at - colon - 1);
            _endpointUrl = "ftp://" + urlWithoutProtocol.Substring(at + 1).TrimEnd('/');
        }

        public void Send(StateReport report)
        {
            var payload = JsonConvert.SerializeObject(report);
            var tempName = Path.GetTempFileName();
            var jsonName = Path.ChangeExtension(tempName, ".json");
            File.Move(tempName, jsonName);
            File.WriteAllText(jsonName, payload);
            using (WebClient client = new WebClient())
            {
                var uri = new Uri(_endpointUrl);
                var remoteName = $"{_endpointUrl}/{System.Guid.NewGuid().ToString()}-stateReport.json";
                client.Credentials = new NetworkCredential(_username, _password);
                client.UploadFile(remoteName, WebRequestMethods.Ftp.UploadFile, jsonName);
            }
            File.Delete(jsonName);
        }
    }
}

