<commit_before>﻿/* Copyright (c) 2016 Acrolinx GmbH */

using Acrolinx.Sdk.Sidebar.Documents;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Acrolinx.Sdk.Sidebar.Util.Logging;
using System.IO;
using System.Diagnostics;
using Newtonsoft.Json;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace Acrolinx.Sdk.Sidebar
{
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    public class AcrolinxPlugin
    {
        private readonly Microsoft.Web.WebView2.WinForms.WebView2 webView2;
        private readonly AcrolinxSidebar sidebar;

        internal AcrolinxPlugin(Microsoft.Web.WebView2.WinForms.WebView2 webView2, AcrolinxSidebar sidebar)
        {
            Contract.Requires(webView2 != null);
            Contract.Requires(sidebar != null);

            this.Document = new Document();
            this.webView2 = webView2;
            this.sidebar = sidebar;
        }


        public async Task OnAfterObjectSet()
        {
            Logger.AcroLog.Debug("OnAfterObjectSet");

            await sidebar.Eval("window.bridge = chrome.webview.hostObjects.bridge; if (!window.console) { window.console = {} }; window.console.logOld = window.console.log; window.console.log = function(msg) { window.bridge.Log(msg); }");
            await sidebar.Eval("window.bridge = chrome.webview.hostObjects.bridge; window.onerror = function(msg, url, line, col, error) { window.bridge.OnError(msg, url, line, col, error); }");

            await InitAcrolinxStorage();

            await sidebar.Eval("{window.bridge = chrome.webview.hostObjects.bridge; window.acrolinxPlugin =   {requestInit: function(){ window.bridge.requestInit()}, onInitFinished: function(finishResult) {window.bridge.onInitFinished(JSON.stringify(finishResult))}, configure: function(configuration) { window.bridge.configure(JSON.stringify(configuration)) }, requestGlobalCheck: function(options) { window.bridge.requestGlobalCheck(options) }, onCheckResult: function(checkResult) {window.bridge.onCheckResult(JSON.stringify(checkResult)) }, selectRanges: function(checkId, matches) { window.bridge.selectRanges(checkId, JSON.stringify(matches))}, replaceRanges: function(checkId, matchesWithReplacements) { window.bridge.replaceRanges(checkId, JSON.stringify(matchesWithReplacements)) }, download: function(downloadInfo) { window.bridge.download(JSON.stringify(downloadInfo))}, openWindow: function(openWindowParameters) { window.bridge.openWindow(JSON.stringify(openWindowParameters)) }, openLogFile: function() {window.bridge.openLogFile()}}; }");
        }

        private async Task InitAcrolinxStorage()
        {
            var storage = sidebar.Storage.GetAllItems();
            var storageJsonStr = storage.ToString();

            var result = await sidebar.Eval("{window.bridge = chrome.webview.hostObjects.bridge; " +
                "window.memoryStorage = new Map(Object.entries(" + storageJsonStr + ")); " +
                "window.acrolinxStorage = { getItem: function(key) { return window.memoryStorage.get(key); }, " +
                "removeItem: async function(key) {  window.memoryStorage.delete(key); window.bridge.removeItem(key); }, " +
                "setItem: async function(key, data) {  window.memoryStorage.set(key, data); await window.bridge.setItem(key, data); } } }");

            Logger.AcroLog.Info("Local storage intialized");
        }

        public void Log(params dynamic[] o)
        {
            Contract.Requires(o != null);

            Logger.AcroLog.Info("JavaScript Log: " + string.Join(", ", o));
        }


        public void OnError(params dynamic[] o)
        {
            Contract.Requires(o != null);
            Contract.Requires(o.Length >= 5);

            Logger.AcroLog.Debug("onError");
            var l = string.Join(", ", o);
            try
            {
                var message = o[4].message as string;<commit_msg>DEv-30489; fix: add debug log for storage sync<commit_after>﻿/* Copyright (c) 2016 Acrolinx GmbH */

using Acrolinx.Sdk.Sidebar.Documents;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Acrolinx.Sdk.Sidebar.Util.Logging;
using System.IO;
using System.Diagnostics;
using Newtonsoft.Json;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace Acrolinx.Sdk.Sidebar
{
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    public class AcrolinxPlugin
    {
        private readonly Microsoft.Web.WebView2.WinForms.WebView2 webView2;
        private readonly AcrolinxSidebar sidebar;

        internal AcrolinxPlugin(Microsoft.Web.WebView2.WinForms.WebView2 webView2, AcrolinxSidebar sidebar)
        {
            Contract.Requires(webView2 != null);
            Contract.Requires(sidebar != null);

            this.Document = new Document();
            this.webView2 = webView2;
            this.sidebar = sidebar;
        }


        public async Task OnAfterObjectSet()
        {
            Logger.AcroLog.Debug("OnAfterObjectSet");

            await sidebar.Eval("window.bridge = chrome.webview.hostObjects.bridge; if (!window.console) { window.console = {} }; window.console.logOld = window.console.log; window.console.log = function(msg) { window.bridge.Log(msg); }");
            await sidebar.Eval("window.bridge = chrome.webview.hostObjects.bridge; window.onerror = function(msg, url, line, col, error) { window.bridge.OnError(msg, url, line, col, error); }");

            await InitAsyncAcrolinxStorage();

            await sidebar.Eval("{window.bridge = chrome.webview.hostObjects.bridge; window.acrolinxPlugin =   {requestInit: function(){ window.bridge.requestInit()}, onInitFinished: function(finishResult) {window.bridge.onInitFinished(JSON.stringify(finishResult))}, configure: function(configuration) { window.bridge.configure(JSON.stringify(configuration)) }, requestGlobalCheck: function(options) { window.bridge.requestGlobalCheck(options) }, onCheckResult: function(checkResult) {window.bridge.onCheckResult(JSON.stringify(checkResult)) }, selectRanges: function(checkId, matches) { window.bridge.selectRanges(checkId, JSON.stringify(matches))}, replaceRanges: function(checkId, matchesWithReplacements) { window.bridge.replaceRanges(checkId, JSON.stringify(matchesWithReplacements)) }, download: function(downloadInfo) { window.bridge.download(JSON.stringify(downloadInfo))}, openWindow: function(openWindowParameters) { window.bridge.openWindow(JSON.stringify(openWindowParameters)) }, openLogFile: function() {window.bridge.openLogFile()}}; }");
        }

        private async Task InitAsyncAcrolinxStorage()
        {
            var storage = sidebar.Storage.GetAllItems();
            var storageJsonStr = storage.ToString();

            var result = await sidebar.Eval("{window.bridge = chrome.webview.hostObjects.bridge; " +
                "window.memoryStorage = new Map(Object.entries(" + storageJsonStr + ")); " +
                "window.acrolinxStorage = { getItem: function(key) { return window.memoryStorage.get(key); }, " +
                "removeItem: async function(key) {  window.memoryStorage.delete(key); window.bridge.removeItem(key); }, " +
                "setItem: async function(key, data) {  window.memoryStorage.set(key, data); await window.bridge.setItem(key, data); } } }");

            if (result == null)
            {
                Logger.AcroLog.Error("Local storage intialized failed. ");
                Logger.AcroLog.Debug("Async storage script: " + storageJsonStr);
            }
            
        }

        public void Log(params dynamic[] o)
        {
            Contract.Requires(o != null);

            Logger.AcroLog.Info("JavaScript Log: " + string.Join(", ", o));
        }


        public void OnError(params dynamic[] o)
        {
            Contract.Requires(o != null);
            Contract.Requires(o.Length >= 5);

            Logger.AcroLog.Debug("onError");
            var l = string.Join(", ", o);
            try
            {
                var message = o[4].message as string;
{'fraction_non_alphanumeric': 0.12443411232105714, 'fraction_numerical': 0.0042823932460540805, 'mean_word_length': 3.2286601138127264, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '800083', 'n_tokens_mistral': 2297, 'n_tokens_neox': 2230, 'n_words': 416}