export default (editor, options) => {
  editor.TraitManager.addType('switch', {
    onChange(e) {
      const { name } = this.model.attributes;
      const value = e.target.checked;
      let sp;
      let node;
      if (name == 'backNode') {
        const { attributes } = this.target.attributes;
        sp = attributes.sp;
        node = attributes.node;
      }
      if (value) {
        this.$switch.addClass('checked');
        if (!sp && node) {
          this.target.addAttributes({sp: node, node: undefined})
        }
      } else {
        this.$switch.removeClass('checked');
        if (sp && !node) {
          this.target.addAttributes({sp: undefined, node: sp})
        }
      }
      this.model.set('value', value);
    },

    getInputEl() {
      if (!this.$switch) {
        const { model, target } = this;
        const { name } = model.attributes;
        let value = model.getTargetValue();
        if (value == '') {
          value = target.attributes.backNode;
        }
        let el = `
          <div class="switch${value ? ' checked' : ''}">
            <div class="switch-track"></div>
            <div class="switch-thumb-underlay">
              <div class="switch-thumb"></div>
              <input type="checkbox" name="${name}"${value ? ' checked="checked"' : ''} />
            </div>
          </div>
        `;

        this.switch = el;
        this.$switch = $(el);
      }
  
      return this.$switch;
    },

    onValueChange() {
      const mod = this.model;
      this.setInputValue(mod.get('value'));
    },

    setInputValue(value) {
      if (!!value) {
        this.$switch.addClass('checked').find('input[type=checked]').prop('checked', !!value);
      } else {
        this.$switch.removeClass('checked').find('input[type=checked]').prop('checked', !!value);
      }
    },

    renderField() {
      const el = this.getInputEl().get(0);
      this.$el.find('.' + this.ppfx + 'field').append(el);
    },
  })
}