using System.Text;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models;
using Microsoft.VisualStudio.Services.WebApi.Patch;
using Microsoft.VisualStudio.Services.WebApi.Patch.Json;
using WebApi = Microsoft.TeamFoundation.WorkItemTracking.WebApi;

namespace Mesa_Backlog.Library;

public class WorkItemTrackingHttpClient
{

    private static void AddPatch(JsonPatchDocument document, string path, object value) => document.Add(new JsonPatchOperation { From = null, Operation = Operation.Add, Path = path, Value = value });
    private static void ReplacePatch(JsonPatchDocument document, string path, object value) => document.Add(new JsonPatchOperation { From = null, Operation = Operation.Replace, Path = path, Value = value });

    public static (string, JsonPatchDocument) GetCreate(bool development, FIBacklogMesa fIBacklogMesa)
    {
        JsonPatchDocument result = new();
        string state = "New";
        string iterationPath = $@"Mesa_FI\{fIBacklogMesa.Status}";
        string systemAreaPath = $@"Mesa_FI\{fIBacklogMesa.SystemS}";
        string title = fIBacklogMesa.Title.Length > 254 ? fIBacklogMesa.Title[..255] : fIBacklogMesa.Title;
        string priority = fIBacklogMesa.Priority switch { "BugFix" => "1", "High" => "1", "Med" => "2", "Low" => "3", "TBD" => "4", _ => "4" };
        string workItemType = fIBacklogMesa.Priority switch { "BugFix" => "Bug", "High" or "Med" or "Low" or "TBD" => "Feature", _ => "Feature" };
        StringBuilder systemInfo = new();
        _ = systemInfo.
            Append("Req : ").Append(fIBacklogMesa.Req).Append("<br />").
            Append("Requestor : ").Append(fIBacklogMesa.Requestor).Append("<br />").
            Append("Submitted : ").Append(fIBacklogMesa.Submitted).Append("<br />").
            Append("Assigned To : ").Append(fIBacklogMesa.AssignedTo).Append("<br />").
            Append("Commit Date : ").Append(fIBacklogMesa.CommitDate).Append("<br />").
            Append("Re-Commit Date : ").Append(fIBacklogMesa.ReCommitDate).Append("<br />").
            Append("UAT as of : ").Append(fIBacklogMesa.UATAsOf).Append("<br />").
            Append("CMP Date : ").Append(fIBacklogMesa.CMPDate);
        string systemAssignedToDisplayName = fIBacklogMesa.Requestor switch
        {
            "Mike" => "Mike.Phares@infineon.com",
            _ => string.Empty
        };
        AddPatch(result, "/fields/System.State", state);
        AddPatch(result, "/fields/System.Title", title);
        // AddPatch(result, "/fields/System.Comment", fIBacklogMesa.Updates);
        AddPatch(result, "/fields/Microsoft.VSTS.Common.Priority", priority);
        AddPatch(result, "/fields/Microsoft.VSTS.TCM.SystemInfo", systemInfo.ToString());
        AddPatch(result, "/fields/System.Description", fIBacklogMesa.Definition);
        if (!development)
            AddPatch(result, "/fields/System.AreaPath", systemAreaPath);
        if (!development)
            AddPatch(result, "/fields/System.IterationPath", iterationPath);
        if (!string.IsNullOrEmpty(fIBacklogMesa.AssignedTo))
            AddPatch(result, "/fields/System.Tags", fIBacklogMesa.AssignedTo);
        if (!string.IsNullOrEmpty(fIBacklogMesa.Submitted) && DateTime.TryParse(fIBacklogMesa.Submitted, out DateTime submitted))
            AddPatch(result, "/fields/System.CreatedDate", submitted.ToString("MM/dd/yyyy hh:mm tt"));
        if (!string.IsNullOrEmpty(systemAssignedToDisplayName))
            AddPatch(result, "/fields/System.AssignedTo", systemAssignedToDisplayName);
        // if (!string.IsNullOrEmpty(fIBacklogMesa.CMPDate) && DateTime.TryParse(fIBacklogMesa.CMPDate, out DateTime completedDate))
        //     AddPatch(result, "/fields/Microsoft.VSTS.Common.ClosedDate", completedDate);
        // if (!string.IsNullOrEmpty(fIBacklogMesa.UATAsOf) && DateTime.TryParse(fIBacklogMesa.UATAsOf, out DateTime uatAsOfDate))
        //     AddPatch(result, "/fields/Microsoft.VSTS.Common.ResolvedDate", uatAsOfDate);
        if (!string.IsNullOrEmpty(fIBacklogMesa.CommitDate) && DateTime.TryParse(fIBacklogMesa.CommitDate, out DateTime commitDate))
            AddPatch(result, "/fields/Microsoft.VSTS.Scheduling.TargetDate", commitDate.ToString("MM/dd/yyyy hh:mm tt"));
        if (!string.IsNullOrEmpty(fIBacklogMesa.EstEffortDays))
            AddPatch(result, "/fields/Microsoft.VSTS.Scheduling.Effort", fIBacklogMesa.EstEffortDays);
        return (workItemType, result);
    }

    public static Task<WorkItem> CreateWorkItem(bool development, WebApi.WorkItemTrackingHttpClient workItemTrackingHttpClient, string project, FIBacklogMesa fIBacklogMesa)
    {
        Task<WorkItem> result;
        (string workItemType, JsonPatchDocument document) = GetCreate(development, fIBacklogMesa);
        result = workItemTrackingHttpClient.CreateWorkItemAsync(document, project, workItemType);
        return result;
    }

    public static JsonPatchDocument GetUpdate(FIBacklogMesa fIBacklogMesa)
    {
        JsonPatchDocument result = new();
        string title = fIBacklogMesa.Title.Length > 254 ? fIBacklogMesa.Title[..255] : fIBacklogMesa.Title;
        ReplacePatch(result, "/fields/System.Title", title);
        ReplacePatch(result, "/fields/System.Description", fIBacklogMesa.Definition);
        return result;
    }

    public static Task<WorkItem> UpdateWorkItem(WebApi.WorkItemTrackingHttpClient workItemTrackingHttpClient, string project, int id, FIBacklogMesa fIBacklogMesa)
    {
        Task<WorkItem> result;
        JsonPatchDocument document = GetUpdate(fIBacklogMesa);
        result = workItemTrackingHttpClient.UpdateWorkItemAsync(document, project, id);
        return result;
    }

}