using Modules.Library.Domain.Entities.MediaContent.CommonProperties;
using Modules.Library.Domain.Entities.MediaContent.Items.Anime;
namespace Modules.Library.Domain.EntityBuilders;

public class AnimeTitleBuilder : EntityBuilder<AnimeTitle>
{
    private static readonly Func<AnimeTitle> CreateInstanceFunc = CreateInstanceFunction();
    private static readonly Action<AnimeTitleBuilder, AnimeTitle> SetInstanceFieldsAction = SetInstanceFieldsAction<AnimeTitleBuilder>();
    

    private CommonPropertiesBuilder? _commonPropertiesBuilder;
    private List<AnimeSeasonBuilder> _seasonBuilders = [];
    private List<AnimeEpisodeBuilder> _episodeBuilders = [];

    private CommonProperties? _commonProperties;
    private readonly List<AnimeItem> _items = [];
    private bool _completed = false;
    private TimeSpan _expirationTime = TimeSpan.Zero;

    public AnimeTitleBuilder SetCommonProperties(CommonPropertiesBuilder builder)
    {
        _commonPropertiesBuilder = builder;
        return this;
    }

    public AnimeTitleBuilder AddEpisode(AnimeEpisodeBuilder builder)
    {
        _episodeBuilders.Add(builder);
        return this;
    }

    public AnimeTitleBuilder AddSeason(AnimeSeasonBuilder builder)
    {
        _seasonBuilders.Add(builder);
        return this;
    }

    public AnimeTitleBuilder Completed()
    {
        _completed = true;
        return this;
    }

    public AnimeTitleBuilder SetExpirationTime(TimeSpan value)
    {
        _expirationTime = value;
        return this;
    }
    /*
    public static AnimeTitleBuilder FromAnimeTitle(AnimeTitle title)
    {
        var builder = new AnimeTitleBuilder();
        builder.SetCommonProperties(CommonPropertiesBuilder.FromCommonProperties(title.CommonProperties));

        foreach (var item in title.Items)
        {
            if (item is AnimeSeason season) builder.AddSeason(AnimeSeasonBuilder.FromAnimeSeason(season));
            else if (item is AnimeEpisode episode) builder.AddEpisode(AnimeEpisodeBuilder.FromAnimeEpisode(episode));
            else throw new NotImplementedException();
        }

        builder.SetCompleted(title.Completed);
        builder.SetDeleted(title.Deleted);
        builder.SetExpirationTime(title.ExpirationTime);
        return builder;
    }
    */

    public override AnimeTitle Build()
    {
        //_title.commonProperties = _commonPropertiesBuilder?.Build() ?? throw new Exception("No commonProperties");
        if (_commonPropertiesBuilder != null) _commonProperties = _commonPropertiesBuilder.BuildObject();
        var title = CreateInstanceFunc();
        _items.AddRange(_seasonBuilders.Select(q => q.BuildObject(title)));
        _items.AddRange(_episodeBuilders.Select(q => q.BuildObject(title, null)));
        SetInstanceFieldsAction(this, title);
        return title;
    }
}