import {
  VuexModule,
  getModule,
  Module,
  Mutation,
  Action,
} from 'vuex-module-decorators'
import { Store } from 'vuex'
import { Track } from '../dto/Track'
import DeliveryTrackingService, {
  getTrackPayload,
} from '../services/DeliveryTrackingService'

@Module({
  name: 'DeliveryTrackingStore',
  namespaced: true,
})
export default class DeliveryTrackingStore extends VuexModule {
  track: null | Track = null
  isLoading = false

  @Mutation
  setTrack(track: null | Track) {
    this.track = track
  }

  @Mutation
  setIsLoading(value: boolean) {
    this.isLoading = value
  }

  @Action({ rawError: true })
  loadTrack(payload: getTrackPayload): Promise<Track> {
    this.setIsLoading(true)

    return DeliveryTrackingService.getTrack(payload)
      .then(track => {
        this.setTrack(track)
        return track
      })
      .finally(() => this.setIsLoading(false))
  }
}

export function getDeliveryTrackingStore(store: Store<any>) {
  return getModule(DeliveryTrackingStore, store)
}
