using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using CommonUsage.Protocols.VDA5050.Messages;
using FundamentalLib;
using Newtonsoft.Json;

namespace CommonUsage.Protocols.VDA5050
{
    public class HTTPCommunication : IVDACommunicationProtocol
    {
        private readonly string _host;
        private readonly int _port;

        public HTTPCommunication(string host, int port)
        {
            _host = host;
            _port = port;
        }

        public async Task PublishConnectionStatus(string status)
        {
            var message = new connectionMessage()
            {
                serialNumber = "test-01",
                headerId = 1,
                timestamp = DateTime.Now,
                connectionState = status
            };

            await SendMessageAsync(message, "vda5050/connection");
        }

        public void SetupOrderListener(Action<orderMessage> orderReceived)
        {
            PicoHttpServer.AddPostTextHandler("/order", new { }, (_, str) =>
            {
                var order = JsonConvert.DeserializeObject<orderMessage>(str);
                orderReceived(order);
                return "";
            });
        }

        public void SetUpInstanActionListener(Action<instanceAction> onInstanceActionReceived)
        {
            PicoHttpServer.AddPostTextHandler("/instanceAction", new { }, (_, str) =>
            {
                var instanceAction = JsonConvert.DeserializeObject<instanceAction>(str);
                onInstanceActionReceived(instanceAction);
                return "";
            });
        }

        public void SetUpImmediateCommandListener(Action<string> onChangeCarFieldsReceived)
        {
            throw new NotImplementedException();
        }

        public async Task SendMessageAsync<T>(T message, string topic)
        {
            try
            {
                var url = $"http://{_host}:{_port}/{topic}";
                using var client = new HttpClient();
                var response = await client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8, "application/json"));

                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine($" >> Sending Message: Failed to send message. Status Code: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error in sending message: {ex.Message}");
            }
        }

        public async Task SendVisualizationMessageAsync<T>(T msg, string topic)
        {
            throw new NotImplementedException();
        }

        public void SetupTestListener(Action<string> testMsg)
        {
            throw new NotImplementedException();
        }
        public async Task PublishFactSheet(factsheetMessage message)
        {
            throw new NotImplementedException();
        }
    }
}
