using AIProofread.core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UtilLib;

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

       private List<WebMessage> actions = new List<WebMessage>();

        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;
            }
            // 添加到队列
            actions.Add(new WebMessage(action, data));
            //this.action = action;
            //this.data = data;
        }

        public void InitializationCompleted()
        {
            if (!this.initialized && actions.Count > 0) // !string.IsNullOrEmpty(this.action)
            {
                actions.ForEach(item =>
                {
                    SendToWeb(item.Message, item.Data);
                });
                // clear
                actions.Clear();
                //SendToWeb(this.action, this.data);
                //this.action = null;
                //this.data = null;
            }
            this.initialized = true;
        }
    }
}
