using AIProofread.core;
using Newtonsoft.Json;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using UtilLib;

namespace AIProofread.Controls
{
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    public partial class FormCommonsenseDetection : BaseWinForm
    {
        private bool initialized = false;

        private string action;
        private object data;

        public FormCommonsenseDetection()
        {
            InitializeComponent();
        }

        private void FormCommonsenseDetection_Load(object sender, EventArgs e)
        {
            // 初始化
            InitWebView(MainWebView, Config.WebPath("commonsense-detection"), "commonsense-detection", () =>
            {
                MainWebView.CoreWebView2.AddHostObjectToScript("detection", CommonSenseDetection.Instance(this));
            });
        }

        private void SendToWeb(string action, object data)
        {
            var json = JsonConvert.SerializeObject(new WebMessage(action, data));
            MainWebView.CoreWebView2.PostWebMessageAsJson(json);
        }

        public void SendMessageToWeb(string action, object data)
        {
            // 判断是否已经初始化完成
            if (this.initialized)
            {
                SendToWeb(action, data);
                return;
            }
            // 添加到队列
            this.action = action;
            this.data = data;
        }

        public void InitializationCompleted()
        {
            if (!this.initialized && !string.IsNullOrEmpty(this.action))
            {
                SendToWeb(this.action, this.data);
                this.action = null;
                this.data = null;
            }
            this.initialized = true;
        }
    }
}
