using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Text;

namespace Infineon.Monitoring.MonA;

public class MonIn : IMonIn, IDisposable
{
    private static readonly DateTime _Utc1970DateTime = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    public const string MonInUrl = "http://moninhttp.{0}.infineon.com/input/text";
    private static readonly Dictionary<string, MonIn> _Instances = new();
    private readonly ExtWebClient _WebClient;
    private readonly string _MonInUrl;
    private static CultureInfo _CultureInfo;

    public static MonIn GetInstance(string url = "http://moninhttp.{0}.infineon.com/input/text")
    {
        MonIn instance;
        if (_Instances.ContainsKey(url))
        {
            instance = _Instances[url];
        }
        else
        {
            lock (_Instances)
            {
                if (!_Instances.ContainsKey(url))
                {
                    instance = new MonIn(url);
                    _Instances.Add(url, instance);
                }
                else
                    instance = _Instances[url];
            }
        }
        return instance;
    }

    private MonIn(string url)
    {
        _WebClient = new ExtWebClient();
        _WebClient.Headers[HttpRequestHeader.ContentType] = "application/text";
        _WebClient.Encoding = Encoding.UTF8;
        _CultureInfo = new CultureInfo("en-US");
        _MonInUrl = url;
    }

    public void SetBasicAuthentication(string username, string password)
    {
        _WebClient.PreAuthenticate = true;
        _WebClient.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
    }

    public string SendStatus(string site, string resource, string stateName, State state) => SendStatus(site, new DateTime?(), resource, string.Empty, stateName, state, string.Empty);

    public string SendStatus(
      string site,
      DateTime timeStamp,
      string resource,
      string stateName,
      State state) => SendStatus(site, new DateTime?(timeStamp), resource, string.Empty, stateName, state, string.Empty);

    public string SendStatus(
      string site,
      string resource,
      string stateName,
      State state,
      string description) => SendStatus(site, new DateTime?(), resource, string.Empty, stateName, state, description);

    public string SendStatus(
      string site,
      DateTime timeStamp,
      string resource,
      string stateName,
      State state,
      string description) => SendStatus(site, new DateTime?(timeStamp), resource, string.Empty, stateName, state, description);

    public string SendStatus(
      string site,
      string resource,
      string subresource,
      string stateName,
      State state) => SendStatus(site, new DateTime?(), resource, subresource, stateName, state, string.Empty);

    public string SendStatus(
      string site,
      DateTime timeStamp,
      string resource,
      string subresource,
      string stateName,
      State state) => SendStatus(site, new DateTime?(timeStamp), resource, subresource, stateName, state, string.Empty);

    public string SendStatus(
      string site,
      string resource,
      string subresource,
      string stateName,
      State state,
      string description) => SendStatus(site, new DateTime?(), resource, subresource, stateName, state, description);

    public string SendStatus(
      string site,
      DateTime? timeStamp,
      string resource,
      string subresource,
      string stateName,
      State state,
      string description)
    {
        string statusMessage = CreateStatusMessage(site, timeStamp, resource, subresource, stateName, state.ToString(), description);
        lock (_WebClient)
            return _WebClient.UploadString(string.Format(_MonInUrl, site), statusMessage);
    }

    public string SendPerformanceMessage(
      string site,
      string resource,
      string performanceName,
      double value) => SendPerformanceMessage(site, new DateTime?(), resource, string.Empty, performanceName, value, string.Empty, string.Empty, new int?());

    public string SendPerformanceMessage(
      string site,
      DateTime? timeStamp,
      string resource,
      string performanceName,
      double value) => SendPerformanceMessage(site, timeStamp, resource, string.Empty, performanceName, value, string.Empty, string.Empty, new int?());

    public string SendPerformanceMessage(
      string site,
      string resource,
      string performanceName,
      double value,
      string description) => SendPerformanceMessage(site, new DateTime?(), resource, string.Empty, performanceName, value, description, string.Empty, new int?());

    public string SendPerformanceMessage(
      string site,
      DateTime? timeStamp,
      string resource,
      string performanceName,
      double value,
      string description) => SendPerformanceMessage(site, timeStamp, resource, string.Empty, performanceName, value, description, string.Empty, new int?());

    public string SendPerformanceMessage(
      string site,
      DateTime? timeStamp,
      string resource,
      string performanceName,
      double value,
      int? interval) => SendPerformanceMessage(site, timeStamp, resource, string.Empty, performanceName, value, string.Empty, string.Empty, interval);

    public string SendPerformanceMessage(
      string site,
      string resource,
      DateTime? timeStamp,
      string performanceName,
      double value,
      string unit) => SendPerformanceMessage(site, timeStamp, resource, string.Empty, performanceName, value, string.Empty, unit, new int?());

    public string SendPerformanceMessage(
      string site,
      DateTime? timeStamp,
      string resource,
      string performanceName,
      double value,
      string unit,
      int? interval) => SendPerformanceMessage(site, timeStamp, resource, string.Empty, performanceName, value, string.Empty, unit, interval);

    public string SendPerformanceMessage(
      string site,
      string resource,
      string subresource,
      string performanceName,
      double value) => SendPerformanceMessage(site, new DateTime?(), resource, subresource, performanceName, value, string.Empty, string.Empty, new int?());

    public string SendPerformanceMessage(
      string site,
      DateTime? timeStamp,
      string resource,
      string subresource,
      string performanceName,
      double value) => SendPerformanceMessage(site, timeStamp, resource, subresource, performanceName, value, string.Empty, string.Empty, new int?());

    public string SendPerformanceMessage(
      string site,
      string resource,
      string subresource,
      string performanceName,
      double value,
      string description) => SendPerformanceMessage(site, new DateTime?(), resource, subresource, performanceName, value, description, string.Empty, new int?());

    public string SendPerformanceMessage(
      string site,
      DateTime? timeStamp,
      string resource,
      string subresource,
      string performanceName,
      double value,
      int? interval) => SendPerformanceMessage(site, timeStamp, resource, subresource, performanceName, value, string.Empty, string.Empty, interval);

    public string SendPerformanceMessage(
      string site,
      DateTime? timeStamp,
      string resource,
      string subresource,
      string performanceName,
      double value,
      string unit) => SendPerformanceMessage(site, timeStamp, resource, subresource, performanceName, value, string.Empty, unit, new int?());

    public string SendPerformanceMessage(
      string site,
      DateTime? timeStamp,
      string resource,
      string subresource,
      string performanceName,
      double value,
      string description,
      string unit,
      int? interval)
    {
        string performanceMessage = CreatePerformanceMessage(site, timeStamp, resource, subresource, performanceName, value, description, unit, interval);
        lock (_WebClient)
            return _WebClient.UploadString(string.Format(_MonInUrl, site), performanceMessage);
    }

    private static string CreateStatusMessage(
      string site,
      DateTime? timeStamp,
      string resource,
      string subresource,
      string stateName,
      string state,
      string description)
    {
        StringBuilder stringBuilder = new();
        if (string.IsNullOrEmpty(subresource))
            _ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" {4} \n{5}", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), stateName.Trim(), state.Trim(), description.Trim());
        else
            _ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" \"{4}\" {5} \n{6}", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), subresource.Trim(), stateName.Trim(), state.Trim(), description.Trim());
        return stringBuilder.ToString();
    }

    private static string CreatePerformanceMessage(
      string site,
      DateTime? timeStamp,
      string resource,
      string subresource,
      string performanceName,
      double value,
      string description,
      string unit,
      int? interval)
    {
        StringBuilder stringBuilder = new();
        if (string.IsNullOrEmpty(subresource))
        {
            if (unit.Equals(string.Empty) && !interval.HasValue)
                _ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" {4} \n{5}", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), performanceName.Trim(), value, description.Trim());
            else
                _ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" {4} {5} {{interval={6}, unit={7}}}\n", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), performanceName.Trim(), value, description.Trim(), interval.HasValue ? interval.Value.ToString() : (object)string.Empty, unit.Trim());
        }
        else if (unit.Equals(string.Empty) && !interval.HasValue)
            _ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" \"{4}\" {5} \n{6}", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), subresource.Trim(), performanceName.Trim(), value, description.Trim());
        else
            _ = stringBuilder.AppendFormat(_CultureInfo, "> {0} {1} \"{2}\" \"{3}\" \"{4}\" {5} {6} {{interval={7}, unit={8}}}\n", site.Trim(), timeStamp.HasValue ? GetDateTimeNowAsPosix(timeStamp.Value) : (object)"now", resource.Trim(), subresource.Trim(), performanceName.Trim(), value, description.Trim(), interval.HasValue ? interval.Value.ToString() : (object)string.Empty, unit.Trim());
        return stringBuilder.ToString();
    }

    private static string GetDateTimeNowAsPosix(DateTime timeStamp)
    {
        if (timeStamp > DateTime.Now)
            timeStamp = DateTime.Now;
        return ((int)timeStamp.ToUniversalTime().Subtract(_Utc1970DateTime).TotalSeconds).ToString(CultureInfo.InvariantCulture);
    }

    public void Dispose()
    {
        KeyValuePair<string, MonIn> keyValuePair = new();
        foreach (KeyValuePair<string, MonIn> instance in _Instances)
        {
            if (instance.Value == this)
            {
                keyValuePair = instance;
                break;
            }
        }
        _ = _Instances.Remove(keyValuePair.Key);
        _WebClient?.Dispose();
    }

}