using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using C1.Silverlight;

namespace SilverTunes
{
    public class FolderTreeItem : C1TreeViewItem
    {
        string _path;
        bool _loaded;

        public FolderTreeItem()
        {
            IsExpandedChanged += (s,e) => Load();
        }

        public string Path
        {
            get
            {
                return _path;
            }
            set
            {
                if (_path != value)
                {
                    _path = value;
                    if (_path.EndsWith("\\"))
                        _path = _path.Substring(0, _path.Length - 1);
                    Header = string.IsNullOrEmpty(_path) ? 
                        "Computer"
                        : (System.IO.Path.GetPathRoot(_path) == _path?
                            _path
                            : System.IO.Path.GetFileName(_path));
                    Items.Clear();
                    Items.Add("Loading...");
                    Load();
                }
            }
        }

        void Load()
        { 
            if(!IsExpanded || _loaded)
            {
                return;
            }
            _loaded = true;
            var media = App.CreateMediaLibraryClient();
            media.DirCompleted += (s, e) =>
            {
                Items.Clear();
                if(e.Result != null)
                {
                    foreach (var dir in e.Result)
                    {
                        Items.Add(new FolderTreeItem { Path = dir });
                    }
                }
            };
            media.DirAsync(Path);
        }
    }
}
