import { Utility } from '../../core/utility';
import './checkbox.sass';

const CHECKBOX_CLASS = 'checkbox';
const RADIOBOX_CLASS = 'radiobox';
const CHECKBOX_INITIALIZED_CLASS = 'checkbox--initialized';

@Utility({
  selector: 'input[type="checkbox"]:not([uw-no-checkbox]), input[type="radio"]:not([uw-no-radiobox])',
})
export class Checkbox {
  constructor(element) {
    if (!element) {
      throw new Error('Checkbox utility cannot be setup without an element!');
    }

    const isRadio = element.type === 'radio';
    const box_class = isRadio ? RADIOBOX_CLASS : CHECKBOX_CLASS;

    if (isRadio && element.closest('.radio-group')) {
      // Don't initialize radiobox, if radio is part of a group
      return false;
    }

    if (element.classList.contains(CHECKBOX_INITIALIZED_CLASS)) {
      // throw new Error('Checkbox utility already initialized!');
      return false;
    }

    if (element.parentElement.classList.contains(box_class)) {
      // throw new Error('Checkbox element\'s wrapper already has class '' + box_class + ''!');
      return false;
    }

    const siblingEl = element.nextSibling;
    const parentEl = element.parentElement;

    const wrapperEl = document.createElement('div');
    wrapperEl.classList.add(box_class);

    const labelEl = document.createElement('label');
    labelEl.setAttribute('for', element.id);

    wrapperEl.appendChild(element);
    wrapperEl.appendChild(labelEl);

    parentEl.insertBefore(wrapperEl, siblingEl);

    element.classList.add(CHECKBOX_INITIALIZED_CLASS);
  }
}
