using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using Aurora.Models.Media;
using Aurora.Services.Settings;
using Aurora.Utils;

namespace Aurora.Services.Library
{
    public class LibraryService : ILibraryService
    {
        #region Fields
        private string _pathName;
        private string _extensions = ".wav,.mp3,.aiff,.flac,.m4a,.m4b,.wma";
        private Dictionary<string, BaseMedia> _library;

        #endregion Fields

        public LibraryService(ISettingsService settingsService)
        {
            _library = new Dictionary<string, BaseMedia>();
            this._pathName = settingsService.LibraryLocation;
            LoadLibrary();
        }

        /// <summary>
        /// Gets the songs.
        /// </summary>
        /// <returns>The songs.</returns>
        public ObservableCollection<BaseMedia> GetLibrary()
        {
            ObservableCollection<BaseMedia> collection = new ObservableCollection<BaseMedia>();
            foreach (KeyValuePair<string, BaseMedia> pair in _library)
            {
                collection.Add(pair.Value);
            }

            return collection;
        }

        public BaseMedia GetSong(string Id)
        {
            _library.TryGetValue(Id, out BaseMedia song);
            return song;
        }

        /// <summary>
        /// Loads library from files.
        /// </summary>
        private void LoadLibrary()
        {
            //Get songs
            List<FileInfo> musicFiles = FileSystemUtils.TraverseFoldersAsync(_pathName, _extensions);

            foreach (FileInfo file in musicFiles)
            {
                TagLib.File tagFile = TagLib.File.Create(file.FullName);

                BaseMedia song = new LocalAudio(file);
                _library.Add(song.Id, song);
            }
        }
    }
}