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

namespace OF_DL.Models.Mappers;

public static class CommonMapper
{
    public static Author? MapAuthor(AuthorDto? dto)
    {
        if (dto == null || dto.Id == 0)
        {
            return null;
        }

        return new Author { Id = dto.Id };
    }

    private static Dash? MapDash(DashDto? dto)
    {
        if (dto == null || (
                string.IsNullOrEmpty(dto.CloudFrontPolicy) &&
                string.IsNullOrEmpty(dto.CloudFrontSignature) &&
                string.IsNullOrEmpty(dto.CloudFrontKeyPairId)))
        {
            return null;
        }

        return new Dash
        {
            CloudFrontPolicy = dto.CloudFrontPolicy,
            CloudFrontSignature = dto.CloudFrontSignature,
            CloudFrontKeyPairId = dto.CloudFrontKeyPairId
        };
    }

    public static Drm? MapDrm(DrmDto? dto)
    {
        if (dto == null || (dto.Manifest == new ManifestDto() && dto.Signature == new SignatureDto()))
        {
            return null;
        }

        return new Drm { Manifest = MapManifest(dto.Manifest), Signature = MapSignature(dto.Signature) };
    }

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

        Full? full = MapFull(dto.Full);
        Preview? preview = MapPreview(dto.Preview);
        Drm? drm = MapDrm(dto.Drm);

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

        return new Files { Full = MapFull(dto.Full), Preview = MapPreview(dto.Preview), Drm = MapDrm(dto.Drm) };
    }

    public static Full? MapFull(FullDto? dto)
    {
        if (dto == null || string.IsNullOrEmpty(dto.Url))
        {
            return null;
        }

        return new Full { Url = dto.Url };
    }

    public static Manifest? MapManifest(ManifestDto? dto)
    {
        if (dto == null || string.IsNullOrEmpty(dto.Dash))
        {
            return null;
        }

        return new Manifest { Dash = dto.Dash };
    }

    public static Preview? MapPreview(PreviewDto? dto)
    {
        if (dto == null || string.IsNullOrEmpty(dto.Url))
        {
            return null;
        }

        return new Preview { Url = dto.Url };
    }

    public static Signature? MapSignature(SignatureDto? dto)
    {
        if (dto == null)
        {
            return null;
        }

        Dash? dash = MapDash(dto.Dash);
        return dash == null ? null : new Signature { Dash = dash };
    }

    public static VideoSources? MapVideoSources(VideoSourcesDto? dto)
    {
        if (dto == null || (string.IsNullOrEmpty(dto._240) && string.IsNullOrEmpty(dto._720)))
        {
            return null;
        }

        return new VideoSources { _240 = dto._240, _720 = dto._720 };
    }
}
