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

export const useSocketStore: StoreDefinition = defineStore('socket', {
  state: () => ({
    connection: null as Socket | null,
    user: null as User | null,
    character: null as Character | null
  }),
  getters: {
    getConnection: (state: any) => state.connection as Socket,
    getUser: (state: any) => state.user as User,
    getCharacter: (state: any) => state.character as Character
  },
  actions: {
    setupSocketConnection() {
      this.connection = io(config.server_endpoint, {
        withCredentials: true,
        transports: ['websocket'],
        reconnectionAttempts: 5
      })

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

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

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

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

      this.user = null
      this.character = null

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

/**
 * Resources:
 * https://www.dynetisgames.com/2017/03/06/how-to-make-a-multiplayer-online-game-with-phaser-socket-io-and-node-js/
 * https://runthatline.com/pinia-watch-state-getters-inside-vue-components/
 * https://pinia.vuejs.org/
 */
