using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace Azyobuzi.Twirunrun
{
    public class Previewer
    {
        private static ScriptEngine engine;

        static Previewer()
        {
            engine = Python.CreateEngine();
            engine.Runtime.LoadAssembly(Assembly.GetExecutingAssembly());
        }

        private static Previewer[] previewExtensions;
        public static Previewer[] GetPreviewExtensions()
        {
            if (previewExtensions == null)
                previewExtensions = new DirectoryInfo(Application.StartupPath + @"\extensions\preview")
                    .EnumerateFiles("*.py", SearchOption.TopDirectoryOnly)
                    .Where(_ => (_.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
                    .Select(_ => new Previewer(_.FullName))
                    .ToArray();

            return previewExtensions;
        }

        public Previewer(string filename)
        {
            scope = engine.ExecuteFile(filename);
        }

        private dynamic scope;

        public Tuple<PreviewDataTypes, object> GetPreviewData(string uri)
        {
            var result = scope.GetPreviewData(uri);
            return Tuple.Create((PreviewDataTypes)result.Item1, (object)result.Item2);
        }

        public bool IsUsable(string uri)
        {
            return scope.IsUsable(uri);
        }
    }

    public enum PreviewDataTypes
    {
        Image,
        Text
    }
}
