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'
import AuthService from '@/widgets/messages/services/AuthService'
import { NotifyHelper } from '@/helpers'

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

  isInitialisedWebsocket = false

  @Mutation
  setInitializeWebsocket() {
    this.isInitialisedWebsocket = true
  }

  @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
  loadOpenThreadsCounting() {
    return CountingMessagesService.getCounting(
      MessageFilterType.openedThreads
    ).then(count =>
      this.setCount({ type: MessageFilterType.openedThreads, count })
    )
  }

  @Action
  async initWebsocket() {
    if (this.isInitialisedWebsocket) {
      return
    }

    this.setInitializeWebsocket()

    try {
      const authToken = await AuthService.getAuthToken()
      MessageWebsocketService.init(authToken)
      MessageWebsocketService.onUpdateCounting(payload => {
        this.setCount(payload)
      })
    } catch (e) {
      NotifyHelper.error('Ошибка подключения к сокетам')
    }
  }
}
