import { Module, Mutation, Action, VuexModule } from 'vuex-module-decorators'
import {
  CountingMessages,
  MessageFilterType,
} from '@/widgets/messages/types/CountingMessages'
import CountingMessagesService from '@/widgets/messages/services/CountingMessagesService'
import { UpdateCountingDto } from '@/widgets/messages/dto/UpdateCountingDto'
import MessageWebsocketService from '@/widgets/messages/services/MessageWebsocketService'

@Module({
  name: 'CountingMessagesModule',
  namespaced: true,
})
export default class CountingMessagesModule extends VuexModule {
  counting: CountingMessages = {
    [MessageFilterType.openedThreads]: 0,
    [MessageFilterType.favoriteThreads]: 0,
  }

  @Mutation
  setCount(payload: UpdateCountingDto) {
    this.counting[payload.type] = payload.count
  }

  @Mutation
  increment(type: MessageFilterType) {
    this.counting[type] = (this.counting[type] || 0) + 1
  }

  @Mutation
  decrement(type: MessageFilterType) {
    this.counting[type] = (this.counting[type] || 0) - 1
  }

  @Action
  loadCounting() {
    Object.values(MessageFilterType).forEach(type => {
      if (type === MessageFilterType.subscribedThread) {
        return
      }

      CountingMessagesService.getCounting(type).then(count =>
        this.setCount({ type, count })
      )
    })
  }

  @Action
  initWebsocket(token: string) {
    MessageWebsocketService.init(token)
    MessageWebsocketService.onUpdateCounting(payload => {
      this.setCount(payload)
    })
  }
}
