import { defineStore } from "pinia";
import { usePlayerStore } from "./player";
import { useGameStore } from "./game";

const connectionUrl = 'wss://fish-spot.game.qvinti.net/socket'

export const useWebsocketStore = defineStore("websocket", {
    state: () => ({
        connection: null
    }),
    actions: {
        init(gameId) {
            const player = usePlayerStore()
            const game = useGameStore()
            console.log(game.owner, game.opponent.id, player.id)
            if (game.owner == player.id || game.opponent.id == player.id) {
                window.location.href = window.location.origin + '/lobby/' + game.id
                return
            }
            this.connection = new WebSocket(connectionUrl + "?gameId=" + gameId + "&playerId=" + player.id);
            this.connection.onopen = function (event) {
                console.log(event);
                console.log("Successfully connected websocket server to game: " + gameId);
            };
            this.connection.onmessage = function (event) {
                const player = usePlayerStore()
                const game = useGameStore()
                let data = {}
                try {
                    data = JSON.parse(event.data)
                } catch (e) {
                    return false;
                }
                switch(data.action) {
                    case 'connected':
                        console.log('Recieve connected from ' + data.from)
                        game.connected(data.from)
                        break
                    case 'disconnected':
                        if (data.from == game.owner) {
                            console.log("owner disconected start timer 30 sec and  end game")
                        }
                        if (data.from == game.opponent.id) {
                            console.log("opponent disconected start timer 30 sec and end game")
                        }
                        console.log('Recieve disconnected from ' + data.from)
                        break
                    case 'sync':
                        console.log('Recieve sync from ' + data.from)
                        game.sync(data.game)
                        break
                    case 'join':
                        console.log('Recieve join from ' + data.from)
                        if (game.owner != player.id) return // Only owner can process join
                        game.join(data.from)
                        break
                    case 'welcome': 
                        console.log('Recieve welcome from ' + data.from)
                        game.welcome(data.game)
                        break
                    case 'decline': 
                        console.log('Recieve decline from ' + data.from)
                        break
                    case 'ready': 
                        console.log('Recieve ready from ' + data.from)
                        game.sync(data.game)
                        break
                    case 'checkMove':
                        console.log('Recieve move from ' + data.from)
                        game.checkMove(data.targetCell)
                        break
                    case 'completeMove':
                        game.completeMove(data.move)
                        break
                    default:
                        console.error('Event data target not found')
                }
            };
            this.connection.onclose = (event) => {
                console.log("Server close websocket connection for player " + player.id);
                setTimeout(function () {
                    console.log("Try reconnect to websocket server for player " + player.id);
                    useWebsocketStore().init(game.id);
                }, 1000);
            };
        },
        send(data) {
            console.log('send', JSON.stringify(data) )
            this.connection.send(JSON.stringify(data))
        },
        disconnect() {
            if (this.connection == null) return
           // this.connection.onclose = () => {}
           // this.connection.close()
        },

    }
})