using OF_DL.Models.Dtos.Common;
using OF_DL.Models.Dtos.Streams;
using OF_DL.Models.Entities.Common;
using OF_DL.Models.Entities.Streams;

namespace OF_DL.Models.Mappers;

public static class StreamsMapper
{
    public static Streams FromDto(StreamsDto? dto)
    {
        Streams mapped = new() { HasMore = dto?.HasMore ?? false, TailMarker = dto?.TailMarker };

        if (dto?.List == null)
        {
            return mapped;
        }

        foreach (ListItemDto entry in dto.List)
        {
            mapped.List.Add(MapList(entry));
        }

        return mapped;
    }

    private static ListItem MapList(ListItemDto dto) =>
        new()
        {
            Id = dto.Id,
            PostedAt = dto.PostedAt,
            Author = CommonMapper.MapAuthor(dto.Author),
            Text = dto.Text,
            RawText = dto.RawText,
            Price = dto.Price,
            IsOpened = dto.IsOpened ?? false,
            IsArchived = dto.IsArchived ?? false,
            Media = MapMedia(dto.Media),
            Preview = dto.Preview
        };

    private static List<Medium>? MapMedia(List<MediumDto>? media) =>
        media?.Select(MapMedium).ToList();

    private static Medium MapMedium(MediumDto dto) =>
        new() { Id = dto.Id, Type = dto.Type, CanView = dto.CanView, Files = MapFiles(dto.Files) };

    private static Files? MapFiles(FilesDto? dto)
    {
        if (dto == null)
        {
            return null;
        }

        Full? full = CommonMapper.MapFull(dto.Full);
        Drm? drm = MapDrm(dto.Drm);

        if (full == null && drm == null)
        {
            return null;
        }

        return new Files { Full = full, Drm = drm };
    }

    private static Drm? MapDrm(DrmDto? dto)
    {
        Manifest? manifest = CommonMapper.MapManifest(dto?.Manifest);
        if (manifest == null)
        {
            return null;
        }

        Signature? signature = CommonMapper.MapSignature(dto?.Signature);
        return signature == null ? null : new Drm { Manifest = manifest, Signature = signature };
    }
}
