using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DynamicDetails
{
    // Listing 14-15
    public class DynamicFolder : DynamicObject
    {
        private DirectoryInfo _directory;

        public DynamicFolder(DirectoryInfo directory)
        {
            _directory = directory;
            if (!directory.Exists)
            {
                throw new ArgumentException("Brak katalogu", "directory");
            }
        }

        public DynamicFolder(string path)
            : this(new DirectoryInfo(path))
        {
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            DirectoryInfo[] items = _directory.GetDirectories(binder.Name);
            if (items.Length > 0)
            {
                result = new DynamicFolder(items[0]);
                return true;
            }
            return base.TryGetMember(binder, out result);
        }

        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes,
                                         out object result)
        {
            if (indexes.Length == 1)
            {
                FileInfo[] items = _directory.GetFiles(indexes[0].ToString());
                if (items.Length > 0)
                {
                    result = items[0];
                    return true;
                }
            }
            return base.TryGetIndex(binder, indexes, out result);
        }
    }

    class Examples15_16
    {
        public static void UseDynamicFolderType()
        {
            // Uwaga: jeśli przykład nie działa, to w Twoim katalogu Documents nie ma pliku 'Test.txt'.
            // Listing 14-16
            dynamic c = new DynamicFolder(@"c:\");
            dynamic home = c.Users.Ian;
            FileInfo textFile = home.Documents["Test.txt"];
        }
    }
}
