<template>
  <div v-if="upgradeVersion>0">
    <v-alert type="info" closable rounded="0">
      Vault Upgrade Available!
      <v-btn @click="showDialog=true" size="small">
        Upgrade Now
      </v-btn>
    </v-alert>
    <v-dialog v-model="showDialog">
      <v-card title="Upgrade Vault" width="25em" class="mx-auto">
        <v-card-text>An upgrade to version {{upgradeVersion}} is available for your approval.</v-card-text>
        <v-card-text><v-icon icon="mdi-information" color="yellow"/> Any currently open orders will continue to execute normally.</v-card-text>
        <v-card-actions class="d-flex justify-center">
          <v-btn color='primary' @click="doUpgrade">Upgrade Vault</v-btn>
          <v-btn @click="showDialog=false">Cancel</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-alert v-if="upgradeResult==='SUCCESS'" type="info" closable rounded="0">
      Vault Upgraded Successfully!
    </v-alert>
    <v-alert v-if="upgradeResult && upgradeResult!=='SUCCESS'" type="warning" closable rounded="0">
      Vault upgrade failed! ({{upgradeResult}})
    </v-alert>
  </div>
</template>

<script setup>
import {ref} from "vue";
import {upgradeVault, detectUpgrade} from "@/blockchain/wallet.js";
import {useStore} from "@/store/store.js";

const s = useStore()
const upgradeVersion = ref(0)
const showDialog = ref(false)
const upgradeResult = ref(null)

detectUpgrade().then((version)=>{
  if (version===null) {
    console.log('detectUpgrade failed')
  }
  else if (s.version<version) {
    upgradeVersion.value = version
    console.log(`Vault upgrade available to version ${version}`)
  }
})

async function doUpgrade() {
  showDialog.value = false
  if (!s.upgrade) {
    console.error('no upgrade available')
    return
  }
  const vault = s.vault
  if (!vault) {
    console.error('no vault logged in')
    return
  }
  upgradeVault(vault, s.upgrade).then(()=>{
    upgradeVersion.value = 0
    console.log('vault upgraded')
    upgradeResult.value = 'SUCCESS'
  }).catch((reason)=>{
    upgradeResult.value = reason
  })
}

</script>

<style scoped lang="scss">

</style>
