import {getInputValue} from 'Global/Form/formUtils';

export var InputBranch = {
    initAll: () => {
        // TODO : prevent concurence ?
        for (const input of document.querySelectorAll('[data-form-branch-state="unloaded"]')) {
            input.removeAttribute('data-form-branch-state');
            InputBranch.init( input );

            const selector = document.querySelector('[name="'+input.getAttribute('data-form-branch-dependency')+'"]');
            
            // Note : selector may not be present
            if (selector == null) {
                InputBranch.setBranch( input, input.getAttribute('data-form-branch-default') );
                continue;
            }
            
            InputBranch.setBranch( input,  getInputValue(selector));
        }
    },

    init: (el) => {
        // Prevent double init
        if (typeof el._InputBranch !== 'undefined') {
            return;
        }

        // Store each child
        el._InputBranch = {};
        InputBranch.storeAll(el);
    },

    setBranch: (el, branchKey) =>  {
        // Store current branch
        InputBranch.storeAll(el);

        const child = el._InputBranch[ branchKey ];
        if (child == null) {
            throw 'Invalid branch "'+branchKey+'"';
        }

        // Restore selected branch
        el.appendChild( child );
    },

    storeAll: (el) => {
        // Note : a shallow copy of children is requiered since we use removeChild
        for (const child of [...el.children]) {
            el._InputBranch[ child.getAttribute('data-branch-child') ]
                = child;
            el.removeChild(child);
        }
    },
    _boot: () => {
        // TODO : only activate one listener per branch
        document.addEventListener('change', (event) => {

            const branch = document.querySelector(
                '[data-form-branch-dependency="'+event.target.name+'"]'
            );

            if (! branch) return;

            InputBranch.setBranch(branch, getInputValue(event.target));
        });
    },
    _onPageLoad() {
        // Boot
        InputBranch.initAll();

        // Bind on dom mutation
        const observer = new MutationObserver(function () {
            InputBranch.initAll();
        });
        observer.observe(document.body, {
            attributes: false,
            childList: true,
            subtree: true,
            characterData: false
        });
    }
}