<script>
  import { Checkbox } from 'element-ui';

  export default {
    name: 'TfCheckbox',
    extends: Checkbox,

    inject: {
      $themeCheckboxColor: { default: () => null },
    },

    props: {
      noBranding: {
        type: Boolean,
        default: false,
      },
    },

    computed: {
      /**
       * Return color value as reactive value
       *
       * @returns {string | null}
       */
      themeCheckboxColor() {
        return !this.noBranding && this.$themeCheckboxColor
          ? this.$themeCheckboxColor()
          : null;
      },
    },

    watch: {
      /**
       * when the user focus we need to emit up an event and possibly update our colors
       */
      focus() {
        this.$emit(this.focus ? 'focus' : 'blur');
        this.toggleColors();
      },

      /**
       * when the user checks the box we need to check if we need to update the colors
       */
      isChecked() {
        this.toggleColors();
      },

      /**
       * When we get the users branded colors we need to update the color of this checkbox
       */
      themeCheckboxColor() {
        this.toggleColors();
      },

      /**
       * if the checkbox is disabled we might need to update the checkboxes colors
       */
      disabled() {
        this.$nextTick(() => {
          this.toggleColors();
        });
      },
    },

    mounted() {
      if (this.themeCheckboxColor) {
        this.toggleColors();
      }
    },

    methods: {
      /**
       * Update all the colors, with inline styles if needed.
       */
      toggleColors() {
        const innerEl = this.$el.querySelector('.el-checkbox__inner');
        const colorLabel = this.$el.querySelector('.color-label');

        if (this.disabled) {
          innerEl.removeAttribute('style');
          return;
        }

        if (this.isChecked) {
          innerEl.style.backgroundColor = this.themeCheckboxColor;
          if (colorLabel) {
            colorLabel.style.color = this.themeCheckboxColor;
          }
        } else {
          innerEl.removeAttribute('style');
          if (colorLabel) {
            colorLabel.removeAttribute('style');
          }
        }

        if (!this.focus) {
          innerEl.style.borderColor = this.themeCheckboxColor;
        } else {
          innerEl.style.removeProperty('border-color');
        }
      },
    },
  };
</script>
