<template>
  <fragment>
    <a
      v-if="url"
      v-show="!isHidden"
      class="btn"
      :id="id"
      :href="url"
      target="_blank"
      :class="classes"
      :disabled="!isEnabled"
    >
      <span v-if="icon" class="fa" :class="faIcon"></span>
      <span v-if="label">{{ _label }}</span>
    </a>
    <button
      v-else
      v-show="!isHidden"
      type="button"
      class="btn"
      :id="id"
      :class="classes"
      :disabled="!isEnabled"
      @click="onClick"
      :title="tooltip ? tooltip : false"
      :data-toggle="tooltip ? 'tooltip' : false"
      :data-placement="tooltip ? 'auto bottom' : false"
    >
      <span v-if="icon" class="fa" :class="faIcon"></span>
      <span v-if="label">{{ _label }}</span>
    </button>
  </fragment>
</template>

<script>
import { str2bool } from "../../util";
export default {
  name: "bc-button",
  props: {
    id: {
      type: String,
      default: null,
    },
    label: {
      type: String,
      default: null,
    },
    icon: {
      type: String,
      default: null,
    },
    tooltip: {
      type: String,
      default: null,
    },
    action: {
      type: String,
      default: null,
    },
    url: {
      type: String,
      default: null,
    },
    is_enabled: {
      type: [Boolean, String],
      default: true,
    },
    is_hidden: {
      type: [Boolean, String],
      default: false,
    },
    is_loading: {
      type: [Boolean, String],
      default: false,
    },
  },
  computed: {
    isHidden() {
      return str2bool(this.is_hidden, false);
    },
    isLoading() {
      return str2bool(this.is_loading, false);
    },
    isEnabled() {
      let is_enabled = str2bool(this.is_enabled, true);
      if (this.isLoading) {
        return false;
      } else {
        return is_enabled;
      }
    },
    faIcon() {
      if (this.isLoading) {
        return "fa-circle-o-notch fa-spin";
      }
      if (this.icon) {
        return `fa-${this.icon}`;
      }
      return false;
    },
    _label() {
      if (this.label && this.isLoading) {
        return "Loading";
      } else if (this.label) {
        return this.label;
      }
      return "";
    },
    classes() {
      let classes = "btn-default";
      if (this.action) {
        classes = `btn-${this.action}`;
      }
      if (!this.label) {
        classes += " btn-sq";
      }
      if (this.label && this.icon) {
        // classes += " btn-block";
      }
      return classes;
    },
  },
  methods: {
    onClick() {
      this.$emit("click", true);
    },
  },
};
</script>
