<template>
  <b-modal id="modal-model-info" size="lg" scrollable centered :title="modalTitle" @show="updateInfo" @close="onClose" v-model="showModal">
    <div v-if="actionPending" class="text-center">
      <b-spinner />
    </div>
    <div v-else id="modal-model-info-content">
      <b-table stacked :items="[info]" :fields="infoFields">

        <template #cell(default)="data">
          <b-icon v-if="data.item.default" icon="check" variant="success"></b-icon>
          <b-icon v-else icon="x-square" variant="danger"></b-icon>

        </template>

      </b-table>
      <b-table stacked v-if="info.details" :items="[info.details]"></b-table>
    </div>

    <template #modal-footer>

      <b-button
          variant="success"
          class="float-right"
          size="sm"
          :href="modelDownloadUrl"
          :disabled="!modelDownloadUrl"
      >
        <b-icon icon="download"/>
        Download model
      </b-button>

      <b-button
          variant="success"
          class="float-right"
          size="sm"
          :href="extraDownloadUrl"
          :disabled="!extraDownloadUrl"
      >
        <b-icon icon="download"/>
        Download {{extraType}}
      </b-button>

      <b-button
          variant="warning"
          class="float-right"
          size="sm"
          :disabled="info.default"
          @click="onClickSetAsDefault"
      >
        <b-icon icon="pencil"/>
        Set as default {{info.type}} model
      </b-button>

      <b-button
          variant="danger"
          class="float-right"
          size="sm"
          @click="onClickDelete"
      >
        <b-icon icon="trash"/>
        Delete
      </b-button>

      <b-button
          variant="secondary"
          class="float-right"
          size="sm"
          @click="showModal=false"
      >
        <b-icon icon="door-closed"/>
        Close
      </b-button>

    </template>
  </b-modal>
</template>

<script>
export default {
  name: "ModelModalInfo",
  model: {
    prop: "show",
    event: "change"
  },
  props: {
    id: {
      type: String
    },
    type: {
      type: String
    },
    show: {
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      actionPending: false,
      info: {},
      infoFields: ['id', 'target_class_name', 'timestamp', 'default']
    }
  },
  methods: {
    updateInfo() {
      return new Promise((resolve, reject) => {
        this.info = {}
        this.actionPending = true
        this.$api.get(`/model/${this.type}/${this.id}`).then(({data}) => {
          this.info = data
          this.actionPending = false
          resolve()
        }).catch((error) => {

          if (!error.response) {
            // network error happened
            this.$showToast("Some network error happened.\nCheck logs!")
          } else {
            // server returned bruh moment
            this.$showToast(`The server returned error: ${error.response.status} ${error.response.statusText}\n${error.response.data}`)
          }

          this.actionPending = false
          reject()
        })
      });
    },
    onClose() {
      this.showModal = false;
    },
    onClickSetAsDefault() {
      return new Promise((resolve, reject) => {
        this.actionPending = true
        this.$api.put(`/model/${this.type}/$default`, {id: this.id}).then(() => {

          this.updateInfo().then(() => { // this resets actionPending
            this.$emit("refresh")
            resolve()
          }, reject)
        }).catch((error) => {

          if (!error.response) {
            // network error happened
            this.$showToast("Some network error happened.\nCheck logs!")
          } else {
            // server returned bruh moment
            this.$showToast(`The server returned error: ${error.response.status} ${error.response.statusText}\n${error.response.data}`)
          }

          this.actionPending = false
          reject()
        })
      });



    },
    onClickDelete() {
      this.$emit("delete", {type: this.type, id: this.id})
      this.showModal = false;
    }
  },
  computed: {
    showModal: {
      get() {
        return this.show
      },
      set(v) {
        this.$emit("change", v)
      }
    },
    modelDownloadUrl() {
      if (("files" in this.info) && ("model" in this.info.files)) {
        return process.env.VUE_APP_API_LOCATION + this.info.files.model
      } else {
        return ""
      }
    },
    extraDownloadUrl() {
      if (("files" in this.info) && (this.extraType in this.info.files)) {
        return process.env.VUE_APP_API_LOCATION + this.info.files[this.extraType]
      } else {
        return ""
      }
    },
    extraType() {
      if (this.type === "svm") {
        return "means"
      } else if (this.type === "cnn") {
        return "weights"
      } else {
        return ""
      }
    },
    modalTitle() {
      return `[${this.type.toUpperCase()}] ${this.id}`
    }
  }
}
</script>

<style scoped>

</style>