using System;
using System.Collections.Generic;
using SessionZero.Data.Sztl;

namespace SessionZero.Data
{
    public static class SzObjectFactory
    {
        public static SzObject CreateObject(SzTemplate template)
        {
            ArgumentNullException.ThrowIfNull(template);

            SzObject obj = template switch
            {
                SzDataObjectTemplate _ => new SzDataObject(),
                _ => throw new NotImplementedException($"Cannot create object for template type '{template.TemplateType}'")
            };
            
            obj.TemplateId = template.Id;
            obj.Id = ""; // TODO: This will be replaces with the top level "id" field whenever it gets filled in in the UI
            obj.Uuid = Guid.NewGuid().ToString();
            
            foreach (var field in template.Fields)
            {
                obj.Fields[field.Key] = new SzField
                {
                    Id = field.Value.Id,
                    Type = field.Value.Type,
                    Value = field.Value.DefaultValue,
                    IsTextBlock = field.Value.IsTextBlock
                };
            }
            
            foreach (var group in template.SubGroups)
            {
                obj.FieldGroups[group.Key] = InitializeGroup(group.Value);
            }

            return obj;
        }

        private static SzFieldGroup InitializeGroup(SztlFieldGroup groupTemplate)
        {
            var group = new SzFieldGroup
            {
                Id = groupTemplate.Id
            };
            
            foreach (var field in groupTemplate.Fields)
            {
                group.Fields[field.Key] = new SzField
                {
                    Id = field.Value.Id,
                    Type = field.Value.Type,
                    Value = field.Value.DefaultValue,
                    IsTextBlock = field.Value.IsTextBlock
                };
            }
            
            foreach (var subGroup in groupTemplate.SubGroups)
            {
                group.SubGroups[subGroup.Key] = InitializeGroup(subGroup.Value);
            }

            return group;
        }
    }
}
