<template>
  <div id="itf-app" class="itf-app itf-append-context">
    <slot></slot>
  </div>
</template>
<script>
import { Vue, Component } from 'vue-property-decorator';
import Message from './message';

let globalApp = null;

export default @Component({
  name: 'itfApp',
  components: {},
  provide() {
    return { globalApp: this }; // do not use Provide from vue-property-decorator
  }
})
class itfApp extends Vue {
  created() {
    globalApp = this;
    Vue.prototype.$globalApp = this;
    Vue.prototype.$showSuccess = this.showSuccess.bind(this);
    Vue.prototype.$showError = this.showError.bind(this);
    Vue.prototype.$showMessage = this.showMessage.bind(this);
    Vue.prototype.$try = this.try.bind(this);
  }

  showSuccess(message, title = '') {
    if (typeof document === 'undefined') {
      return;
    }
    return Message.success({
      isCollapsed: false,
      showClose: true,
      supportHTML: true,
      duration: 5000,
      message,
      title,
      position: 'bottom-center',
    });
  }

  showError(message, opts = {}) {
    if (typeof document === 'undefined') {
      return;
    }
    return Message.error({
      isCollapsed: false,
      showClose: true,
      supportHTML: true,
      duration: 30000,
      message,
      position: 'bottom-center',
      ...opts
    });
  }

  showMessage(options) {
    if (typeof document === 'undefined') {
      return;
    }
    return Message.toast({
      isCollapsed: false,
      showClose: true,
      supportHTML: true,
      duration: -1,
      position: 'bottom-right',
      ...options
    });
  }

  async try(func, errFunc = null) {
    try {
      await func();
    } catch (err) {
      if (err.code !== 'ERR_CANCELED') {
        console.error(err);
        if (!err.noMessage) this.showError(err.message);
        if (errFunc) {
          errFunc(err);
        }
      }
    }
  }
}
</script>
