using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace ControlExplorer.Controls.FlexGrid
{
    public sealed partial class MediaLibrary : UserControl
    {
        private List<Song> _songs;

        public MediaLibrary()
        {
            this.InitializeComponent();
            BindMediaGrid();
        }

        // load songs into the grid
        async void BindMediaGrid()
        {
            // load songs
            _songs = await MediaLibraryStorage.Load();

            // build view
            var view = new C1.Xaml.C1CollectionView(_songs);
            view.GroupDescriptions.Add(new C1.Xaml.PropertyGroupDescription("Artist"));
            view.GroupDescriptions.Add(new C1.Xaml.PropertyGroupDescription("Album"));

            // configure grid
            var fg = _flexMedia;
            fg.CellFactory = new MusicCellFactory();
            fg.MergeManager = null; // << review this, should not merge cells with content
            fg.Columns["Duration"].ValueConverter = new SongDurationConverter();
            fg.Columns["Size"].ValueConverter = new SongSizeConverter();
            fg.ItemsSource = view;

            // show media library summary
            UpdateSongStatus();
            view.VectorChanged += (s, e) => { UpdateSongStatus(); };
        }

        // update song status
        void UpdateSongStatus()
        {
            var view = _flexMedia.ItemsSource as C1.Xaml.IC1CollectionView;
            var songs = view.OfType<Song>();
            _txtSongs.Text = string.Format("{0:n0} Artists; {1:n0} Albums; {2:n0} Songs; {3:n0} MB of storage; {4:n2} days of music.",
                (from s in songs select s.Artist).Distinct().Count(),
                (from s in songs select s.Album).Distinct().Count(),
                songs.Count(),
                (double)(from s in songs select s.Size / 1024.0 / 1024.0).Sum(),
                (double)(from s in songs select s.Duration / 1000.0 / 3600.0 / 24.0).Sum());
        }

        // converter for artist/album groups
        public class GroupHeaderConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, string culture)
            {
                // return group name only (no counts)
                var group = value as ICollectionViewGroup;
                if (group != null && targetType == typeof(string))
                {
                    return group.Group.ToString();
                }

                // default
                return value;
            }
            public object ConvertBack(object value, Type targetType, object parameter, string culture)
            {
                throw new NotImplementedException();
            }
        }

        // converter for song durations (stored in milliseconds)
        public class SongDurationConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, string culture)
            {
                var ts = TimeSpan.FromMilliseconds((long)value);
                return ts.Hours == 0
                    ? string.Format("{0:00}:{1:00}", ts.Minutes, ts.Seconds)
                    : string.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
            }
            public object ConvertBack(object value, Type targetType, object parameter, string culture)
            {
                throw new NotImplementedException();
            }
        }

        // converter for song sizes (return x.xx MB)
        public class SongSizeConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, string culture)
            {
                return string.Format("{0:n2} MB", (long)value / 1024.0 / 1024.0);
            }
            public object ConvertBack(object value, Type targetType, object parameter, string culture)
            {
                throw new NotImplementedException();
            }
        }
    }
}
