import { Action, Module, Mutation, VuexModule } from 'vuex-module-decorators'
import { NotifyHelper } from '@/helpers'
import {
  Manager,
  ManagerCollection,
  ManagerCollectionsByGroup,
} from '@/types/Manager'
import ManagerService from '@/widgets/tasks/http/services/ManagerService'

@Module({
  name: ManagerModule.storeName,
  namespaced: true,
})
export class ManagerModule extends VuexModule {
  static storeName = 'tasks/ManagerModule'

  managersCollection: ManagerCollection = {}
  managerCollectionsByGroup: ManagerCollectionsByGroup = {}

  get getManagerByUid() {
    return (managerUid: string): Manager => this.managersCollection[managerUid]
  }

  get managersAsArray(): Manager[] {
    return Object.values(this.managersCollection)
  }

  @Mutation
  setManagerCollectionsByGroup(collection: ManagerCollectionsByGroup) {
    this.managerCollectionsByGroup = collection
  }

  @Mutation
  setManagers(managers: ManagerCollection) {
    this.managersCollection = managers
  }

  @Action
  loadManagers() {
    return ManagerService.loadManagers()
      .then(managersGroups => {
        this.setManagerCollectionsByGroup(managersGroups)

        let collection: ManagerCollection = {}

        Object.values(managersGroups).forEach(collectionPart => {
          collection = { ...collection, ...collectionPart }
        })

        this.setManagers(collection)
      })
      .catch(() => NotifyHelper.error('Ошибка загрузки сотрудников'))
  }
}
