<template>
  <div class="form-group">
    <label
      :for="id"
      class="toggle form-control"
      :class="{ checked: isChecked }"
    >
      <span class="toggle-switch">{{ label }}</span>
      <input
        type="checkbox"
        :name="inputValue"
        :value="inputValue"
        class="toggle-trigger"
        :id="id"
        :disabled="!isEnabled"
        :checked="isChecked"
        @input="onInput"
      />
      <span class="toggle-output"></span>
    </label>
    <p v-if="help" class="help-block">{{ help }}</p>
  </div>
</template>

<script>
import { str2bool } from "../../util";
export default {
  name: "bc-toggle",
  props: {
    id: {
      type: String,
      default: null,
    },
    label: {
      type: String,
      default: null,
    },
    value: {
      type: [Boolean, String],
      default: null,
    },
    info: {
      type: String,
      default: null,
    },
    tooltip: {
      type: String,
      default: null,
    },
    help: {
      type: String,
      default: null,
    },
    validation: {
      type: String,
      default: null,
    },
    is_enabled: {
      type: [Boolean, String],
      default: true,
    },
    is_hidden: {
      type: [Boolean, String],
      default: false,
    },
    is_required: {
      type: [Boolean, String],
      default: false,
    },
    is_valid: {
      type: [Boolean, String],
      default: null,
    },
  },
  data() {
    return {
      inputValue: null,
    };
  },
  mounted() {
    this.inputValue = str2bool(this.value);
    this.$emit("input", this.inputValue);
  },
  updated() {
    this.inputValue = str2bool(this.value);
  },
  computed: {
    isRequired() {
      return str2bool(this.is_required);
    },
    isValid() {
      return str2bool(this.is_valid, null);
    },
    isHidden() {
      return str2bool(this.is_hidden, false);
    },
    isEnabled() {
      return str2bool(this.is_enabled, true);
    },
    isChecked() {
      return str2bool(this.value);
    },
  },
  methods: {
    onInput(event) {
      let checked = event.target.checked;
      this.inputValue = checked;
      this.$emit("input", checked);
    },
  },
};
</script>