import { tpl } from './switchTpl';
import './switch.scss';
const Switch = (($) => {
  const defaultConfig = {
    node: document.querySelector('body'),
    id: '',
    size: '',
    theme: '',
    className: '',
    initState: true,
    beforeRender: null,
    afterRender: null,
    beforeDispose: null,
    afterDispose: null,
    onStateChange: null,
  };
  class Switch {
    static getElement(elemString) {
      let element;
      let div = document.createElement('div');
      div.innerHTML = elemString.trim();
      element = div.childNodes;
      div = null;
      return element
    }
    constructor(config) {
      this.config = $.extend({}, defaultConfig, config);
      this.name = 'Switch';
      this.element = null;
      this.render();
    }
    getState() {
      const { element } = this;
      return element.querySelector('input[type="checkbox"]').checked;
    }
    setState(state) {
      const { element } = this;
      if (typeof state !== 'boolean') {
        return false;
      }
      element.querySelector('input[type="checkbox"]').checked = state;
    }
    toggleState() {
      const { element } = this;
      const isChecked = element.querySelector('input[type="checkbox"]').checked;
      element.querySelector('input[type="checkbox"]').checked = !isChecked;
    }
    render() {
      const {
        id,
        node,
        size,
        className,
        initState,
        afterRender,
        beforeRender,
        onStateChange
      } = this.config;
      const config = {
        id: '',
        size: '',
        checked: '',
        className,
      };
      this.switchChange = () => {
        if (typeof onStateChange === 'function') {
          onStateChange(this.getState());
        }
      };
      if (id !== '') {
        config.id = ` id=${id}`;
      }
      switch (size) {
        case 'sm':
          config.size = 'cd-switch-sm';
          break;
        default:
          break;
      }
      if (initState) {
        config.checked = 'checked';
      }
      if (typeof beforeRender === 'function') {
        beforeRender();
      }
      this.element = Switch.getElement(template.render(tpl, config))[0];
      node.appendChild(this.element);
      if (typeof afterRender === 'function') {
        afterRender();
      }
      this.element
        .querySelector('input[type="checkbox"]')
        .addEventListener('change', this.switchChange, {
          capture: false
        });
    }
    dispose() {
      let { element } = this;
      const {
        beforeDispose,
        afterDispose
      } = this.config;
      if (typeof beforeDispose === 'function') {
        beforeDispose();
      }
      element.querySelector('input[type="checkbox"]').removeEventListener('change', this.switchChange);
      element.parentNode.removeChild(this.element);
      element = null;
      if (typeof afterDispose === 'function') {
        afterDispose();
      }
    }
  }
  return Switch
})($);
export default Switch;