using System;
using System.Collections.Generic;
using C4IT.FASD.Base;
using C4IT.Logging;
using FasdDesktopUi.Basics;
using static C4IT.Logging.cLogManager;

namespace FasdDesktopUi.Basics.Helper
{
    internal static class TicketDeepLinkHelper
    {
        internal static bool TryOpenTicketRelationExternally(cF4sdApiSearchResultRelation relation)
        {
            try
            {
                if (relation == null || relation.Type != enumF4sdSearchResultClass.Ticket)
                    return false;

                var ticketConfig = cFasdCockpitConfig.Instance?.Global?.TicketConfiguration;
                if (ticketConfig == null)
                    return false;

                var activityType = GetActivityType(relation);
                var openExternally = ShouldOpenExternally(ticketConfig, activityType);

                if (!openExternally)
                    return false;

                var url = BuildTicketDeepLink(relation.id, activityType);
                if (string.IsNullOrWhiteSpace(url))
                    return false;

                new cBrowsers().Start("default", url);
                return true;
            }
            catch (Exception ex)
            {
                LogException(ex);
            }

            return false;
        }

        private static string GetActivityType(cF4sdApiSearchResultRelation relation)
        {
            if (relation?.Infos != null && relation.Infos.TryGetValue("ActivityType", out var activityTypeValue))
                return activityTypeValue;

            return null;
        }

        private static bool ShouldOpenExternally(cF4sdTicketConfig ticketConfig, string activityType)
        {
            if (ticketConfig == null)
                return false;

            if (TryGetOverride(ticketConfig.OpenActivitiesExternallyOverrides, activityType, out var overrideValue))
                return overrideValue;

            return ticketConfig.OpenActivitiesExternally;
        }

        private static bool TryGetOverride(IEnumerable<string> overrides, string activityType, out bool value)
        {
            value = false;

            if (string.IsNullOrWhiteSpace(activityType) || overrides == null)
                return false;

            foreach (var entry in overrides)
            {
                if (string.IsNullOrWhiteSpace(entry))
                    continue;

                var parts = entry.Split(new[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length != 2)
                    continue;

                var typeName = parts[0].Trim();
                if (!string.Equals(typeName, activityType, StringComparison.OrdinalIgnoreCase))
                    continue;

                if (!TryParseBool(parts[1], out value))
                    return false;

                return true;
            }

            return false;
        }

        private static bool TryParseBool(string value, out bool result)
        {
            result = false;
            if (string.IsNullOrWhiteSpace(value))
                return false;

            switch (value.Trim().ToLowerInvariant())
            {
                case "true":
                case "1":
                case "yes":
                    result = true;
                    return true;
                case "false":
                case "0":
                case "no":
                    result = false;
                    return true;
                default:
                    return bool.TryParse(value, out result);
            }
        }

        internal static string BuildTicketDeepLink(Guid ticketId, string activityType)
        {
            if (ticketId == Guid.Empty)
                return null;

            var server = cCockpitConfiguration.Instance?.m42ServerConfiguration?.Server;
            if (string.IsNullOrWhiteSpace(server))
                return null;

            var baseUrl = server.TrimEnd('/');
            if (!baseUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
                !baseUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            {
                baseUrl = "https://" + baseUrl;
            }
            if (!baseUrl.EndsWith("/wm", StringComparison.OrdinalIgnoreCase))
                baseUrl += "/wm";

            if (string.IsNullOrWhiteSpace(activityType))
                return null;

            var viewOptionsJson = $"{{\"embedded\":false,\"objectId\":\"{ticketId}\",\"type\":\"{activityType}\",\"viewType\":\"preview\",\"archived\":0}}";
            var viewOptionsEncoded = Uri.EscapeDataString(viewOptionsJson);

            return $"{baseUrl}/app-ServiceDesk/?view-options={viewOptionsEncoded}";
        }
    }
}
