import placeholder from '../util/placeholder';
import dom from '../util/dom';

function update(form) {
    let orgType = form.querySelector('[data-id="org_type"] select').value;
    let requiresClientId = orgType === 'education' || orgType === 'charity';
    let isPartnerOrganization = orgType === 'partner_organization' || orgType === 'cloud_partner';

    dom.toggleAttribute(
        form.querySelector('[data-id="client_id"]'),
        'hidden', !requiresClientId
    );
    dom.toggleAttribute(
        form.querySelector('[data-id="person_id"]'),
        'hidden', !requiresClientId
    );
    dom.toggleAttribute(
        form.querySelector('[data-id="partner_id"]'),
        'hidden', !isPartnerOrganization
    );

    dom.toggleAttribute(
        form.querySelector('[data-id="client_id"] [name]'),
        'required', requiresClientId
    );
    dom.toggleAttribute(
        form.querySelector('[data-id="person_id"] [name]'),
        'required', requiresClientId
    );
    dom.toggleAttribute(
        form.querySelector('[data-id="partner_id"] [name]'),
        'required', isPartnerOrganization
    );
}

function render(form) {
    if (!form || form.dataset.activated)
        return;

    placeholder.updateAll(form);

    form.querySelector('[data-id="org_type"] select')
        .addEventListener('change', () => { update(form); });

    update(form);
    form.dataset.activated = true;
}

function renderAll() {
    Array.from(document.querySelectorAll('form[data-id="org_type"]'))
        .forEach(render);
}

renderAll();

export default { render };