namespace Harmonia.Core.Tags;

public class TagLibTagResolver : ITagResolver
{
    public SongTagInfo GetSongTagInfo(string fileName)
    {
        var songTagInfo = new SongTagInfo();

        using (var tagFile = TagLib.File.Create(fileName))
        {
            byte? discNumber = null;
            byte? trackNumber = null;
            ushort? year = null;

            if (tagFile.Tag.Track > 0)
                trackNumber = (byte)tagFile.Tag.Track;

            if (tagFile.Tag.Disc > 0)
                discNumber = (byte)tagFile.Tag.Disc;

            if (tagFile.Tag.Year > 0)
                year = (ushort)tagFile.Tag.Year;

            songTagInfo.Title = tagFile.Tag.Title;
            songTagInfo.Album = tagFile.Tag.Album;
            songTagInfo.Artists = [.. tagFile.Tag.Performers.Select(x => x.Trim())];
            songTagInfo.AlbumArtists = [.. tagFile.Tag.AlbumArtists.Select(x => x.Trim())];
            songTagInfo.DiscNumber = discNumber;
            songTagInfo.TrackNumber = trackNumber;
            songTagInfo.Length = tagFile.Properties.Duration;
            songTagInfo.Year = year;
            songTagInfo.Genre = tagFile.Tag.JoinedGenres;
            songTagInfo.BitRate = (uint)tagFile.Properties.AudioBitrate;
            songTagInfo.SampleRate = (uint)tagFile.Properties.AudioSampleRate;

            foreach (var picture in tagFile.Tag.Pictures)
            {
                if (picture.Type == TagLib.PictureType.NotAPicture)
                    continue;

                var pictureTag = new PictureTag()
                {
                    MimeType = picture.MimeType,
                    PictureType = (PictureType)picture.Type,
                    Data = picture.Data.Data
                };

                songTagInfo.Pictures.Add(pictureTag);
            };
        }

        return songTagInfo;
    }
}