import AAUtils from "../../util/util";

const formType = 'aa-admin-collection-wrap';
function initPlugin(el, defaultOptions, libs) {
    let formWrap = el.classList.contains(formType) ? el : el.closest('.aa-admin-collection-wrap');
    if (formWrap === null) {
        console.error('could not create collection plugin');
        return;
    }

    let collectionEl = formWrap.querySelector(':scope .aa-admin-collection');
    let addButtons = formWrap.querySelectorAll(':scope .aa-admin-collection-add');
    let createPlugin = function () {
        return {
            collectionEl: collectionEl,
            addButton: addButtons[addButtons.length - 1],
            collectionIndex: 0,
            deleteBtnLabel: 'delete',
            init() {
                this.addButton.addEventListener('click', plugin.addItemListener.bind(this));

                if (this.collectionEl.dataset.formIndex) {
                    this.collectionIndex = parseInt(this.collectionEl.dataset.formIndex);
                } else {
                    this.collectionIndex = this.collectionEl.children.length;
                }

                this.deleteBtnLabel = this.collectionEl.dataset.formEntryDeleteLabel;

                this.allowAdd = '1' === this.collectionEl.dataset.formAllowAdd;
                this.allowDelete = '1' === this.collectionEl.dataset.formAllowDelete;
                this.allowSort = '1' === this.collectionEl.dataset.formAllowSort;

                if (!this.allowAdd && this.addButton) {
                    this.addButton.styles.display = 'none';
                }

                let items = this.collectionEl.querySelectorAll(':scope > *');
                [...items].forEach((item) => {
                    this.decorateCollectionItem(item)
                });

                this._applyCollectionIndex();
            },
            addItemListener(e) {
                e.preventDefault();
                let prototype = this.collectionEl.dataset.prototype;

                // Replace '__name__' in the prototype's HTML to
                // instead be a number based on how many items we have
                let newForm = prototype.replace(/__name__/g, this.collectionIndex + 1);

                let newFormEl = AAUtils.createElementFromHTML(newForm);

                this.collectionEl.appendChild(newFormEl);
                this.decorateCollectionItem(newFormEl);

                if (AAForm) {
                    AAForm.initialize(newFormEl.parentNode);
                }

                this.collectionIndex = this.collectionIndex + 1;

                return false;
            },
            decorateCollectionItem(item) {
                item.classList.add('aa-admin-collection-item');

                let actionBar = AAUtils.createElementFromHTML(
                    ''
                    + '<div class="aa-admin-collection-item-actions">'
                    + '</div>'
                );
                item.appendChild(actionBar);

                if (this.allowSort) {
                    let upButton = AAUtils.createElementFromHTML(
                        ''
                        + '<button class="btn btn-sm btn-primary aa-admin-collection-up" tabindex="-1">'
                        + '▲'
                        + '</button>'
                    );
                    upButton.addEventListener('click', this._handleMoveUp.bind(this));
                    actionBar.appendChild(upButton);

                    let downButton = AAUtils.createElementFromHTML(
                        ''
                        + '<button class="btn btn-sm btn-primary aa-admin-collection-down" tabindex="-1">'
                        + '▼'
                        + '</button>'
                    );
                    downButton.addEventListener('click', this._handleMoveDown.bind(this));
                    actionBar.appendChild(downButton);
                }

                if (this.allowDelete) {
                    let deleteButton = AAUtils.createElementFromHTML(
                        ''
                        + '<button class="btn btn-sm btn-danger aa-admin-collection-delete" tabindex="-1">'
                        + this.deleteBtnLabel
                        + '</button>'
                    );
                    deleteButton.addEventListener('click', this._handleDelete.bind(this));
                    actionBar.appendChild(deleteButton);
                }
            },
            _handleDelete(e) {
                e.preventDefault();

                let btn = e.target;
                let collecItem = btn.closest('.aa-admin-collection-item');

                collecItem.remove();

                this._applyCollectionIndex();

                return false;
            },
            _handleMoveUp(e) {
                e.preventDefault();

                let btn = e.target;
                let collecItem = btn.closest('.aa-admin-collection-item');
                let siblingsArray = Array.from(this.collectionEl.children);
                let index = siblingsArray.indexOf(collecItem);
                if (index > 0) {
                    this.collectionEl.insertBefore(collecItem, siblingsArray[index - 1]);
                }

                this._applyCollectionIndex();

                return false;
            },
            _handleMoveDown(e) {
                e.preventDefault();

                let btn = e.target;
                let collecItem = btn.closest('.aa-admin-collection-item');
                let siblingsArray = Array.from(this.collectionEl.children);
                let index = siblingsArray.indexOf(collecItem);
                if (index < (siblingsArray.length - 1)) {
                    this.collectionEl.insertBefore(collecItem, siblingsArray[index + 1 + 1]);
                }

                this._applyCollectionIndex();

                return false;
            },
            _applyCollectionIndex() {
                let items = this.collectionEl.querySelectorAll('.aa-admin-collection-item');
                let index = 0;
                [...items].forEach((item) => {
                    let collectionIndexEl = item.querySelector(['[name$="[collection_index]"]']);
                    if (collectionIndexEl) {
                        collectionIndexEl.value = index;
                        index++;
                    }
                });
            }
        }
    };


    let plugin = createPlugin();
    plugin.init();

    return plugin;
}

AAForm.addTypeHandler(formType, initPlugin);