/*
 * Copyright (C) 2016-2020 Kano Computing Ltd.
 * License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { WidgetDiv } from '@kano/kwc-blockly/blockly.js';
import { StampsField } from '../../../../blockly/fields/stamps-field.js';
import { BlocklyValueStepHelper } from './value.js';
import { BeaconWidget } from '../../../../challenge/widget/beacon.js';
import { throttle } from '../../../../decorators.js';
import { FieldSample } from '../../../../parts/parts/speaker/blockly/field-sample.js';
class IndexedPickerBeaconWidget extends BeaconWidget {
    getPosition() { return 'picker-target:0,50'; }
    getDomNode() {
        const node = super.getDomNode();
        node.style.zIndex = '200000';
        return node;
    }
}
export class IndexedPickerFieldStepHelper extends BlocklyValueStepHelper {
    constructor() {
        super(...arguments);
        this.beacon = null;
    }
    testCase(challenge, step) {
        const field = this.getField(challenge, step);
        return field && (field.constructor === StampsField || field.constructor === FieldSample);
    }
    test(challenge, step) {
        if (!super.test(challenge, step)) {
            return false;
        }
        return this.testCase(challenge, step);
    }
    setupBeacon(challenge) {
        if (!this.beacon) {
            this.beacon = new IndexedPickerBeaconWidget();
            challenge.editor.addContentWidget(this.beacon);
            const engineBeacon = challenge.widgets.get('beacon');
            if (engineBeacon) {
                const node = engineBeacon.getDomNode();
                node.style.opacity = '0';
            }
        }
    }
    removeBeacon(challenge) {
        if (this.beacon) {
            challenge.editor.removeContentWidget(this.beacon);
            this.beacon = null;
            const engineBeacon = challenge.widgets.get('beacon');
            if (engineBeacon) {
                const node = engineBeacon.getDomNode();
                node.style.opacity = '';
            }
        }
    }
    enter(challenge, step) {
        const field = this.getField(challenge, step);
        const options = field.getOptions();
        let targetItems = [];
        Object.values(options).forEach((item) => {
            item.resources.forEach(el => targetItems.push(el));
        });
        if (!challenge.workspace) {
            return;
        }
        const getItem = this.getItem.bind(this);
        this.tagHandler = challenge.editor.queryEngine.registerTagHandler('picker-target', () => {
            return {
                getHTMLElement() {
                    const item = getItem(step.validation.blockly.value.value, targetItems);
                    if (!item) {
                        return field.getSvgRoot();
                    }
                    item.scrollIntoView({ behavior: 'smooth' });
                    return item;
                },
                getId() { return 'picker-target'; }
            };
        });
        // Listen to changes in the editor. For each change, add or remove the beacon
        this.listener = (e) => {
            const scrollingEl = this.getScrollingElement();
            if (!scrollingEl) {
                return;
            }
            scrollingEl.addEventListener('scroll', (event) => this.onScroll(event, challenge));
            const item = this.getItem(step.validation.blockly.value.value, targetItems);
            if (item) {
                this.setupBeacon(challenge);
            }
            else {
                this.removeBeacon(challenge);
            }
        };
        challenge.workspace.addChangeListener(this.listener);
    }
    leave(challenge, step) {
        if (this.listener && challenge.workspace) {
            challenge.workspace.removeChangeListener(this.listener);
        }
        if (this.beacon) {
            challenge.editor.removeContentWidget(this.beacon);
            this.beacon = null;
        }
        if (this.tagHandler) {
            this.tagHandler.dispose();
        }
    }
    getItem(id, targetItems) {
        const shadow = this.getShadowElement();
        if (!shadow) {
            return;
        }
        const items = shadow.querySelectorAll('.item');
        const item = Array.from(items).find(item => item.id === id);
        return item;
    }
    getIdFromValue(value, targetItems) {
        const item = targetItems.find((el) => value === el.label);
        let id = '';
        if (item && item.id) {
            id = item.id;
        }
        return id;
    }
    getShadowElement() {
        if (!WidgetDiv || !WidgetDiv.DIV || !WidgetDiv.DIV.firstChild) {
            return;
        }
        const picker = WidgetDiv.DIV.firstChild;
        const shadow = picker.shadowRoot;
        if (!shadow) {
            return;
        }
        return shadow;
    }
    getScrollingElement() {
        const shadow = this.getShadowElement();
        if (!shadow) {
            return;
        }
        const scrollingEl = shadow.querySelector('.items');
        return scrollingEl;
    }
    onScroll(e, challenge) {
        if (challenge && challenge.workspace) {
            challenge.workspace.fireChangeListener(e);
        }
    }
}
__decorate([
    throttle(500)
], IndexedPickerFieldStepHelper.prototype, "onScroll", null);
//# sourceMappingURL=indexed-picker.js.map