using System;
using System.IO;
using System.Threading.Tasks;

namespace Aurora.Models.Media
{
    public class LocalAudio : BaseMedia
    {
        public LocalAudio(FileInfo fileInfo)
        {
            File = fileInfo;
            LoadMetadata();
        }

        public LocalAudio(LocalAudio copy)
        {
            File = copy.File;
            LoadMetadata();
        }

        #region Properties
        public FileInfo File { get; private set; }

        public override BaseMetadata Metadata { get; protected set; }

        public override MediaTypeEnum MediaType
        {
            get { return MediaTypeEnum.Audio; }
        }

        #endregion Properties

        /// <summary>
        /// Override load method.
        /// </summary>
        public override async Task Load()
        {
            if (this.DataStream != null)
            {
                DataStream.Close();
                DataStream = null;
            }
            this.DataStream = System.IO.File.OpenRead(File.FullName);
            await base.Load();
        }

        /// <summary>
        /// Override unload method
        /// </summary>
        public override void Unload()
        {
            if (this.DataStream != null)
            {
                DataStream.Close();
                DataStream = null;
            }
            base.Unload();
        }

        private void LoadMetadata()
        {
            TagLib.File tagFile = TagLib.File.Create(File.FullName);

            Metadata = new AudioMetadata()
            {
                Title = tagFile.Tag.Title,
                Album = tagFile.Tag.Album,
                Artist = tagFile.Tag.FirstAlbumArtist,
                ExtraData = tagFile.Tag
            };
        }
    }
}