import { Component, Inject, Vue } from 'vue-property-decorator'
import { TaskModule } from '@/widgets/tasks/modules/TaskModule'
import { Task } from '@/widgets/tasks/types/Task'
import { LoadTasksPayload } from '@/widgets/tasks/http/dto/LoadTasksPayload'
import { RouteNames } from '@/widgets/tasks/router/routeNames'

@Component
export default class BaseTasksPage extends Vue {
  @Inject('TaskModule')
  taskModule!: TaskModule

  isInitialLoading = false
  initialPayload!: LoadTasksPayload
  lastLoadedTasksLength = 0

  get tasks(): Task[] {
    return this.taskModule.tasks
  }

  async infinityLoad(index: number, done: Function) {
    const tasks = await this.taskModule.infinityLoadTasks(
      this.initialPayload as LoadTasksPayload
    )

    this.lastLoadedTasksLength = tasks.length

    done(tasks.length === 0)
  }

  get isDisableInfinity() {
    return this.isInitialLoading || !this.lastLoadedTasksLength
  }

  initialLoad() {
    this.isInitialLoading = true

    return this.taskModule
      .loadTasks(this.initialPayload as LoadTasksPayload)
      .finally(() => (this.isInitialLoading = false))
  }

  toIndexRoute() {
    this.$router.push({ name: RouteNames.tasks })
  }

  toNewTaskPage() {
    this.$router.push({ name: RouteNames.createTask })
  }

  activated() {
    this.initialLoad()
  }

  deactivated() {
    this.lastLoadedTasksLength = 0
    this.isInitialLoading = false
  }
}
