import { defineStore } from 'pinia'
import { io, Socket } from 'socket.io-client'
import type { Character, User } from '@/types'
import config from '@/config'
import { useCookies } from '@vueuse/integrations/useCookies'

export const useGameStore = defineStore('game', {
  state: () => ({
    screen: 'login',
    token: '' as string | null,
    connection: null as Socket | null,
    user: null as User | null,
    character: null as Character | null
  }),
  actions: {
    setScreen(screen: string) {
      this.screen = screen
    },
    initConnection() {
      this.connection = io(config.server_endpoint, {
        secure: !config.development,
        withCredentials: true,
        transports: ['websocket'],
        reconnectionAttempts: 5
      })

      // Let the server know the user is logged in
      this.connection.emit('login')

      // set user
      this.connection.on('logged_in', (user: User) => {
        this.setUser(user)
      })

      // When we can't reconnect, disconnect
      this.connection.on('reconnect_failed', () => {
        this.disconnectSocket()
      })
    },
    disconnectSocket() {
      if (!this.connection) return

      this.connection.disconnect()
      this.connection = null

      this.token = null
      this.user = null
      this.character = null

      useCookies().remove('token')
    },
    setToken(token: string) {
      this.token = token
    },
    setUser(user: User | null) {
      this.user = user
    },
    setCharacter(character: Character | null) {
      this.character = character
    }
  }
})
