using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PXP.Crawler.API.Designers.Property;
using PXP.Crawler.API.Model;
using PXP.Crawler.API.Plugins.Net.Chrome.Controls;
using Skybound.Gecko;

namespace PXP.Crawler.API.Plugins.Net.Chrome
{
    [NodeInfo("Javascript", typeof(ChromeJavascriptNode), Category = "Chrome", Description = "Executes javascript on browser...")]
    public class ChromeJavascriptNode : Node
    {
        private ChromeControl chrome;
        private GeckoWebBrowser webBrowser;
        private bool hasBrowser = false;
        private SimpleObjectForScripting scrObj;

        public ChromeJavascriptNode(Program program) : base(program)
        {
            Code = "";
        }

        public override void CreateDesigner()
        {
            base.CreateDesigner();
            base.designer.Control.BackColor = Color.Peru;
        }

        private void ExecuteCode(string jsCode)
        {
            if (jsCode.Length > 0)
            {
                if (hasBrowser)
                {                    
                    scrObj.RunRawJavaScriptOnClient(jsCode, false);                    
                }
            }
        }

        [NodePin(NodePin.NodePinDirection.Input)]
        [Browsable(false)]
        public ChromeControl Chrome
        {
            get { return chrome; }
            set
            {
                chrome = value;
                if (chrome == null)
                {
                    webBrowser = null;
                    hasBrowser = false;
                    scrObj = null;
                }
                else
                {
                    webBrowser = chrome.webBrowser;
                    hasBrowser = true;
                    scrObj = webBrowser.Window.CreateScriptObject();
                }
            }
        }

        internal string code = "";


        [Category("Javascript")]
        [Editor(typeof(CodePropertyEditor), typeof(UITypeEditor))]
        [CodePropertyDefault(@"alert('test');")]
        [NodePin(NodePin.NodePinDirection.Input)]
        public string Code {
            get
            {
                return code;
            }
            set
            {
                code = value;
            } 
        }

        [NodePin(NodePin.NodePinDirection.Input)]
        [Category("Javascript")]
        [Browsable(false)]
        public bool Execute
        {
            get
            {
                return false;
            }
            set
            {
                if (value)
                {
                    ExecuteCode(Code);
                }
            }
        }
    }
}
