using e_suite.API.Common.models;
using e_suite.API.Common;
using e_suite.Database.Core.Tables.Glossaries;

namespace e_suite.Modules.GlossariesManager;

public static class GlossaryItemHelper
{
    public static async Task<GlossaryItem?> TranslateToGlossaryItem(Glossary glossary, ICustomFieldHelper customFieldHelper, CancellationToken cancellationToken)
    {
        var result = new GlossaryItem
        {
            Id = glossary.Id,
            Guid = glossary.Guid,
            Name = glossary.Name,

        };

        if (glossary.Parent != null)
        {
            result.Parent = await TranslateToGlossaryItem(glossary.Parent, customFieldHelper, cancellationToken);
        }

        var customFieldDefinitions = new List<CustomFieldDefinition>();
        foreach (var customField in glossary.CustomFieldDefinitions)
        {
            customFieldDefinitions.Add(await customFieldHelper.TranslateToCustomFieldDefinitionAsync(customField.CustomField, cancellationToken));
        }

        result.ChildCustomFieldDefinition = customFieldDefinitions;

        if (result.ChildCustomFieldDefinition.Count == 0)
            result.ChildCustomFieldDefinition = null;

        var customFieldValues = await customFieldHelper.CustomFieldValuesList(glossary.CustomFieldValues, cancellationToken);
        result.CustomFieldValues = customFieldValues;

        if (result.CustomFieldValues?.Count == 0)
            result.CustomFieldValues = null;

        return result;
    }
}