import { querySelectorAllDeep } from 'query-selector-shadow-dom';
import cssStyle from "./cssStyle";
import RuleService from "../domain/RuleService";

export default class ActionProbabilityView {

    stylesheetElement: Element;

    constructor() {
        this.stylesheetElement = null;
    } 

    show(ruleService: RuleService, elementActionListMap): void {
        this.attachStyleSheet(document.head);
        for (const [dom_element, rules] of ruleService.elementRules) {
            const rootNode = dom_element.getRootNode()
            if (rootNode !== document) {
                this.attachStyleSheet(rootNode);
            }
            dom_element.setAttribute("aifex_frequency", null);
            dom_element.setAttribute("aifex_style", "true");

            for (const rule of rules) {
                dom_element.setAttribute(`aifex_${rule.prefix}`, "true");
            }
        }
        
        for (const [element, actionList] of elementActionListMap) {
            let maxProbability = 0;
            for (let action of actionList) {
                if (action.probability > maxProbability) {
                    maxProbability = action.probability;
                }
            }
            if (maxProbability > 0.6) {
                element.setAttribute("aifex_frequency", "often")
            } else if (maxProbability > 0.3) {
                element.setAttribute("aifex_frequency", "sometimes")
            } else if (maxProbability > 0.01) {
                element.setAttribute("aifex_frequency", "rarely")
            } else {
                element.setAttribute("aifex_frequency", "never")
            }
        }
    }

    hide() {
        const dom_elements = querySelectorAllDeep("[aifex_style]")
        for (const dom_element of dom_elements) {
            dom_element.removeAttribute("aifex_frequency");
            dom_element.removeAttribute("aifex_style");
        }
    }

    private attachStyleSheet(node) {
        const nodeChilds: Element[] = Array.from(node.children);
        if (nodeChilds.some(node => node.hasAttribute("aifex_stylesheet"))) {
            return;
        }
        if (this.stylesheetElement) {
            node.appendChild(this.stylesheetElement.cloneNode(true));
        } else {
            this.stylesheetElement = document.createElement("style");
            this.stylesheetElement.setAttribute("type", "text/css");
            this.stylesheetElement.setAttribute("aifex_stylesheet", "true");
    
            const cssNode = document.createTextNode(cssStyle);
            this.stylesheetElement.appendChild(cssNode);
            node.appendChild(this.stylesheetElement);
        }
    }

}