using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Net.Http;
using System.Text;
using VitrosConsole.FolderWatcher;
using VitrosConsole.Parser;
using VitrosConsole.Persistence;
using VitrosConsole.Port;
using System.Text.Json;
using Model.Models.VitrosModels;

namespace VitrosConsole
{
    public class Application
    {
        private readonly ILogger _logger;
        private readonly IConfiguration _configuration;
        private readonly FolderWatcherService _folderWatcherService;
        private readonly VitrosParser _vitrosParser;
        private readonly PersistenceService _persistenceService;
        private readonly SerialPortListener _serialPortListener;

        public Application(ILogger<Application> logger,
                           IConfiguration configuration,
                           FolderWatcherService folderWatcherService,
                           VitrosParser vitrosParser,
                           PersistenceService persistenceService,
                           SerialPortListener serialPortListener)
        {
            _logger = logger;
            _configuration = configuration;
            _folderWatcherService = folderWatcherService;
            _vitrosParser = vitrosParser;
            _persistenceService = persistenceService;
            _serialPortListener = serialPortListener;
        }
        public void Start()
        {
            string folderPath = _configuration.GetSection("FolderPath").Value;

            FileSystemWatcher folderWatcher = _folderWatcherService.GetFolderWatcher(folderPath);

            folderWatcher.Created += new FileSystemEventHandler(OnVitrosFileAdded);

            //SerialPort vitrosSerialPort = _serialPortListener.GetSerialPort();

            //vitrosSerialPort.DataReceived += new SerialDataReceivedEventHandler(OnDataReceived);

            //vitrosSerialPort.Open();

            //_logger.LogInformation($"listening on {vitrosSerialPort.PortName}");
        }
        private void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort serialPort = (SerialPort)sender;
            string data = serialPort.ReadLine();
            Console.WriteLine("Data: " + data);
            WriteToFile(data);
        }
        private void WriteToFile(string data)
        {
            string folderToDump = _configuration.GetSection("FolderPath").Value;

            var fileName = folderToDump + DateTime.Now.ToShortDateString();

            using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Read))
            {
                using (var sr = new StreamWriter(fs))
                {
                    sr.WriteLine(data);
                }
            }
        }
        private async void OnVitrosFileAdded(object sender, FileSystemEventArgs e)
        {
            string filePath = e.FullPath;

            _logger.LogInformation($"Detected new file. {filePath}");

            List<Sample> samples = _vitrosParser.Parse(filePath);

            //_persistenceService.Save(samples);

            //string machineCode = _configuration.GetSection("MachineCode").Value;
            string machineCode = "V250";

            string jsonContent = JsonSerializer.Serialize(samples);

            HttpClient httpClient = new HttpClient();

            string danpheApiUrl = $"https://localhost:44377/Vitros/ReceiveSample?MachineCode={machineCode}";

            var vistrosSampleDataPost = new HttpRequestMessage(HttpMethod.Post, danpheApiUrl)
            {
                Content = new StringContent(jsonContent, Encoding.UTF8, "application/json")  //application/json 
            };

            _logger.LogInformation($"{samples.Count} Samples saved to Database");

            var samplePostResult = await httpClient.SendAsync(vistrosSampleDataPost);

            bool isRequestSuccessfull = samplePostResult.IsSuccessStatusCode;
        }
    }
}
