require("dotenv").config();
const express = require("express");
const mariadb = require("mariadb");

const router = express.Router();

// Create MariaDB connection pool
const pool = mariadb.createPool({
    host: process.env.MARIA_HOST,
    user: process.env.MARIA_USER,
    password: process.env.MARIA_PASS,
    database: process.env.MARIA_DBNM,
    connectionLimit: 5
});
 
const getGameData = async (req, res) => {
    let conn;
    let items = 'ws2gamelink';
    try {
        const { wsname } = req.query;
        if (!items || !wsname) {
            return res.status(400).json({ error: "Missing items or wsname parameter" });
        }

        console.log("Fetching game data from table:", items);

        conn = await pool.getConnection();

        // Fetching the first dataset
        const ws2gamelinkQuery = `SELECT * FROM \`${items}\` WHERE wsname = ?`;
        const rows = await conn.query(ws2gamelinkQuery, [wsname]);

        if (!rows.length) {
            return res.status(404).json({ error: "No data found" });
        }

        let gamelinkArray = rows[0].gamelink;

        // Ensure gamelinkArray is an array
        if (typeof gamelinkArray === "string") {
            gamelinkArray = [gamelinkArray]; // Convert to array if it's a string
        }
        if (!Array.isArray(gamelinkArray)) {
            return res.status(500).json({ error: "Invalid gamelink data format" });
        }

        const gameDataResults = [];

        for (const link of gamelinkArray) {
            const gameLinkParts = link.split('/');
            let gameNameFromUrl = '';
            let gameIdData = '';
            let gameTableName = '';
            let gameVersion = '';

            if (gameLinkParts.length === 5) {
                gameNameFromUrl = gameLinkParts[3];
                gameIdData = gameLinkParts[4].split('=')[1]; // Extracting ID
            } else if (gameLinkParts.length === 6) {
                gameNameFromUrl = gameLinkParts[3];
                gameVersion = gameLinkParts[4];
                gameIdData = gameLinkParts[5].split('=')[1]; // Extracting ID
            }

            if (gameNameFromUrl === 'drawing' && gameVersion === 'v2') {
                gameTableName = 'game_drawing_v2';
            } else if (gameNameFromUrl === 'drawing' && gameVersion === 'v3') {
                gameTableName = 'game_drawing_v3';
            } else if (gameNameFromUrl === 'drawing' && gameVersion === 'drawing_writo') {
                gameTableName = 'drawing_writo';
            } else if (gameNameFromUrl === 'drawing' && gameVersion === 'drawing_phonics') {
                gameTableName = 'drawing_phonics';
            } else if (gameNameFromUrl === 'drawing') { 
                gameTableName = 'game_drawing';  // General case, only if no version is specified
            } else if (gameNameFromUrl === 'drag' && gameVersion === 'v2') {
                gameTableName = 'game_drag_v2';
            } else if (gameNameFromUrl === 'drag' && gameVersion === 'v4') {
                gameTableName = 'game_drag_v4';
            } else if (gameNameFromUrl === 'drag' && gameVersion === 'dragdrop_phonics') {
                gameTableName = 'drag_drop_phonics';
            } else if (gameNameFromUrl === 'drag' && gameVersion === 'match_phonics') {
                gameTableName = 'drag_phonics';
            } else if (gameNameFromUrl === 'drag') {
                gameTableName = 'game_drag';  // General case for "drag"
            } else if (gameNameFromUrl === 'tick' && gameVersion === 'tick_phonics_v1') {
                gameTableName = 'tick_phonics_option_6';
            } else if (gameNameFromUrl === 'tick' && gameVersion === 'tick_phonics_v2') {
                gameTableName = 'tick_phonics_option_9';
            } else if (gameNameFromUrl === 'tick' && gameVersion === 'tick_phonics_v3') {
                gameTableName = 'game_tick_v3_phonics';
            } else if (gameNameFromUrl === 'tick' && gameVersion === 'v1') {
                gameTableName = 'game_tick_variant1';
            } else if (gameNameFromUrl === 'tick' && gameVersion === 'v2') {
                gameTableName = 'game_tick_variant2';
            } else if (gameNameFromUrl === 'tick' && gameVersion === 'v3') {
                gameTableName = 'game_tick_varient3';
            } else if (gameNameFromUrl === 'cross' && gameVersion === 'cross_phonics_v1') {
                gameTableName = 'cross_phonics_option_6';
            } else if (gameNameFromUrl === 'cross' && gameVersion === 'cross_phonics_v2') {
                gameTableName = 'cross_phonics_option_9';
            } else if (gameNameFromUrl === 'cross' && gameVersion === 'v1') {
                gameTableName = 'game_cross_varient1';
            } else if (gameNameFromUrl === 'cross' && gameVersion === 'v2') {
                gameTableName = 'game_cross_varient2';
            } else if (gameNameFromUrl === 'cross' && gameVersion === 'v3') {
                gameTableName = 'game_cross_varient3';
            }




            // else if (gameNameFromUrl === 'cross' && gameVersion === 'v2') {
            //     gameTableName = 'game_cross_varient2';
            // }
            



            

            // console.log('Game Info:', { gameTableName, gameVersion, gameIdData });

            if (gameTableName && gameIdData) {
                let gameConn;
                try {
                    gameConn = await pool.getConnection();
                    const gameDataQuery = `SELECT * FROM \`${gameTableName}\` WHERE id = ?`;
                    const gameDataRows = await gameConn.query(gameDataQuery, [gameIdData]);
                    gameDataResults.push({ link, data: gameDataRows });
                } catch (gameError) {
                    console.error("Error fetching game data:", gameError);
                } finally {
                    if (gameConn) gameConn.release();
                }
            }
        }

        res.json({ wsData: rows, gameData: gameDataResults });
    } catch (err) {
        console.error("Database error:", err);
        res.status(500).json({ error: "Database error" });
    } finally {
        if (conn) conn.release();
    }
};

module.exports = getGameData;
