using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace Azyobuzi.Twirunrun
{
    public class Previewer
    {
        private static ScriptEngine engine = Python.CreateEngine();

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

            return previewExtensions;
        }

        public Previewer(string filename)
        {
            Source = engine.CreateScriptSourceFromFile(filename);
        }

        public ScriptSource Source { private set; get; }

        public bool GetPreviewerInfo(string uri, out Tuple<PreviewDataTypes, object> result)
        {
            lock (engine)
            {
                var args = new PreviewExtensionArgs(uri);

                var scope = engine.CreateScope();
                scope.SetVariable("args", args);

                Source.Execute(scope);

                result = Tuple.Create(args.Type, args.Result);
                return args.IsMatch;
            }
        }
    }

    public enum PreviewDataTypes
    {
        Image,
        Text
    }

    public class PreviewExtensionArgs
    {
        public PreviewExtensionArgs(string uri)
        {
            this.Uri = uri;
        }

        public string Uri { private set; get; }

        public bool IsMatch { set; get; }

        public PreviewDataTypes Type { set; get; }

        private object result;
        public object Result
        {
            set
            {
                if (value is Image || value is string)//Image or Text
                    result = value;
                else
                    throw new ArgumentException("ResultにはImage型、もしくはString型以外のオブジェクトは設定できません。");
            }
            get
            {
                return result;
            }
        }
    }
}
