'use strict';

import * as chai from 'chai';
import {getDocument} from "../../../../source/dom/util.mjs";
import {chaiDom} from "../../../util/chai-dom.mjs";
import {initJSDOM} from "../../../util/jsdom.mjs";

let expect = chai.expect;
chai.use(chaiDom);

describe('ImageEditor', function () {
    this.timeout(10000);

    let ImageEditor, document;
    let registerCustomElement;
    let CustomElement;
    let assembleMethodSymbol;

    before(async function () {
        await initJSDOM({});

        const domModule = await import("../../../../source/dom/customelement.mjs");
        registerCustomElement = domModule['registerCustomElement'];
        CustomElement = domModule['CustomElement'];
        assembleMethodSymbol = domModule['assembleMethodSymbol'];

        const componentModule = await import("../../../../source/components/content/image-editor.mjs");
        ImageEditor = componentModule['ImageEditor'];
        document = getDocument();
    });

    beforeEach(() => {
        let mocks = document.getElementById('mocks');
        mocks.innerHTML = '<div id="target"></div>';
    });

    afterEach(() => {
        let mocks = document.getElementById('mocks');
        mocks.innerHTML = '';
    });

    it('should not double-call attributeChangedCallback for readonly', function (done) {
        const htmlTAG = 'monster-image-editor-observed-test';

        class ObservedImageEditor extends ImageEditor {
            static getTag() {
                return htmlTAG;
            }

            get defaults() {
                return Object.assign({}, super.defaults, {
                    shadowMode: false,
                    templates: {
                        main: '<div id="image-editor-test"></div>'
                    }
                });
            }

            [assembleMethodSymbol]() {
                return CustomElement.prototype[assembleMethodSymbol].call(this);
            }

            constructor() {
                super();
                this.attributeChangedCalls = [];
            }

            attributeChangedCallback(name, oldValue, newValue) {
                this.attributeChangedCalls.push([name, oldValue, newValue]);
            }
        }

        registerCustomElement(ObservedImageEditor);

        let element = document.createElement(htmlTAG);
        document.getElementById('target').appendChild(element);

        element.attributeChangedCalls = [];
        element.setAttribute('data-monster-readonly', '');

        setTimeout(function () {
            try {
                const readonlyCalls = element.attributeChangedCalls.filter(
                    ([name]) => name === 'data-monster-readonly',
                );
                expect(readonlyCalls).to.have.length(1);
                done();
            } catch (e) {
                done(e);
            }
        }, 20);
    });
});
