<template>
  <v-tooltip bottom>
    <template #activator="{ on }">
      <v-btn
        text
        icon
        :disabled="!activeAssignmentsExist"
        :loading="loading"
        @click="freeLocks"
        v-on="on"
      >
        <v-icon>vpn_key</v-icon>
      </v-btn>
    </template>
    <span>Free all locked Submissions</span>
  </v-tooltip>
</template>

<script>
import { deleteAllActiveAssignments, fetchActiveAssignments } from '@/api'
import { TutorOverview } from '@/store/modules/tutor-overview'

export default {
  name: 'FreeLocksButton',
  data () {
    return {
      activeAssignmentsExist: false,
      loading: false,
      shortPollInterval: null
    }
  },
  async created () {
    this.activeAssignmentsExist = await this.checkForActiveAssignments()
    this.shortPollInterval = setInterval(async () => {
      this.activeAssignmentsExist = await this.checkForActiveAssignments()
    } , 5e3)
  },
  beforeDestroy () {
    clearInterval(this.shortPollInterval)
  },
  methods: {
    async checkForActiveAssignments () {
      return (await fetchActiveAssignments()).length > 0
    },
    async freeLocks () {
      this.loading = true
      await deleteAllActiveAssignments()
      this.loading = false
      // Just lie to the user for now. The actual value will be fetched by the timeout soon.
      this.activeAssignmentsExist = false
    }
  }
}
</script>