<template>
  <button :class="'button ' + classes" :disabled="disabled" :type="type" @click="_onClick" :data-loading="state == 'loading'" :data-loaded="state == 'loaded'">
    <span :class="'button__label ' + iconClass"><span class="button__text">{{text}}</span></span>
    <template v-if="useLoading">
    <span class="button__label--success icon-thumb-up">{{loadedText}}</span>
    <span class="button__spinner"><span class="spinner-holder"><span class="spinner-container"><em><span></span></em></span></span></span>
    </template>
  </button>
</template>

<script>
const SIZE_SMALL = 'small';
const SIZE_MICRO = 'micro';
const CSS_SMALL = 'button--small';
const CSS_MICRO = 'button--micro';
const CSS_STRETCH = 'button--stretch';

export default {
  props: {
    text: {
      type: String,
      default: ''
    },
    loadedText: {
      type: String,
      default: 'Success'
    },
    type: {
      type: String,
      default: 'button'
    },
    useLoading: {
      type: [Boolean, String],
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    class: {
      type: String,
      default: ''
    },
    iconClass: {
      type: String,
      default: ''
    },
    size: {
      type: String,
      default: ''
    },
    stretch: {
      type: Boolean,
      default: false
    }
  },
  data: function () {
    return {
      state: ''
    };
  },
  computed: {
    classes: function () {
      var classes = '';
      if (this.class) {
        classes += ' ' + this.class;
      }
      if (this.size === SIZE_SMALL) {
        classes += ' ' + CSS_SMALL;
      } else if (this.size === SIZE_MICRO) {
        classes += ' ' + CSS_MICRO;
      }
      if (this.stretch) {
        classes += ' ' + CSS_STRETCH;
      }

      return classes;
    }
  },
  methods: {
    activityIndicator: function (promise) {
      this._loading();
      promise.then(this._loadedWithSuccess, this._loadedWithError);
    },
    setLoading: function () {
      this._loading();
    },
    setLoaded: function () {
      this._loadedWithSuccess();
    },
    reset: function () {
      this.state = '';
    },
    _onClick: function (e) {
      if (this.state === 'loading') {
        e.preventDefault();
        return false;
      }

      if (this.state === 'loaded') {
        this.$emit('loaded-click');
        e.preventDefault();
        return false;
      }

      if (this.useLoading) {
        this._loading();
      }
      this.$emit('btn-click');
    },
    _loading: function () {
      this.state = 'loading';
    },
    _loadedWithSuccess: function () {
      this.state = 'loaded';
      this.$emit('action-finished');
    },
    _loadedWithError: function () {
      this.state = '';
      this.$emit('action-finished');
    }
  }
};

</script>
