const net = require('net');

const BlackjackGame = require('./blackjack_game.js');

const server = net.createServer((socket) => {
    // This callback function will be called every time a new client connects to the server
    console.log('Client connected');
    const game = new BlackjackGame();
    // send Start game message to client
    socket.write('Welcome to Blackjack!\nCommands: \n1. New game\n2. Exit\n');

    // Handle incoming data from the client
    socket.on('data', (data) => {
        console.log(`Received data from client: ${data}`);
        console.log(`Type of data: ${typeof data}`)
        console.log(`Data to string: ${data.toString()}`)

        // expected data: 1.(start/play again) 1.exit 2.hit 2.stand
        if (data.toString() === '1') {
            game.dealInitialHands();
            const dict = {
                playerHand: game.playerHand,
                playerScore: game.getHandValue(game.playerHand),
                dealerHand: [game.dealerHand[0],'??'],
                dealerScore: game.getHandValue([game.dealerHand[0]]),
                winner: null
            };
            socket.write(JSON.stringify(dict));
        } 
        else if (data.toString() === '2') {
            socket.write('Thank you for playing!');
            socket.end();
        }
        else if (["hit","h"].includes(data.toString()) && game.hasStarted) {
            game.playerHit();
            // check if player busts
            if (game.getHandValue(game.playerHand) > 21) {
                const json = {
                    playerHand: game.playerHand,
                    playerScore: game.getHandValue(game.playerHand),
                    dealerHand: game.dealerHand,
                    dealerScore: game.getHandValue(game.dealerHand),
                    winner: 'Dealer',
                };
                socket.write(JSON.stringify(json));
                socket.write('Wanna play again?\n1. Yes\n2. No\n');
            }
            else{
                const dict = {
                    playerHand: game.playerHand,
                    playerScore: game.getHandValue(game.playerHand),
                    dealerHand: [game.dealerHand[0],'??'],
                    dealerScore: game.getHandValue([game.dealerHand[0]]),
                    winner: null
                };
                socket.write(JSON.stringify(dict));
            }
        }
        else if (["stand","s"].includes(data.toString()) && game.hasStarted) {
            game.playerStand();
            const dict = {
                playerHand: game.playerHand,
                playerScore: game.getHandValue(game.playerHand),
                dealerHand: game.dealerHand,
                dealerScore: game.getHandValue(game.dealerHand),
                winner: game.determineWinner()
            };
            socket.write(JSON.stringify(dict));
            socket.write('Wanna play again?\n1. Yes\n2. No\n');
        }
        else{
            socket.write(JSON.stringify({error:"Invalid command"}));
        }
    });

    // Handle client disconnection
    socket.on('end', () => {
        console.log('Client disconnected');
    });
});

// Start the server and listen on port 3000
server.listen(3000, () => {
    console.log('Server started on port 3000');
});