import express from 'express';
import pg from 'pg';

// Setup express server
const app = express();
app.use(express.json());

const PORT = process.env.PORT || 3000;

// Create and initialize db connection
const pool = new pg.Pool({
    connectionString: process.env.DATABASE_URL,
});

async function initializeDatabase() {
    try {
        await pool.query(`
      CREATE TABLE IF NOT EXISTS pixels (
        x INTEGER,
        y INTEGER,
        color VARCHAR(7),
        PRIMARY KEY (x, y)
      )
    `);
    } catch (error) {
        console.error('Error initializing database:', error);
    }
}

initializeDatabase();

/**
 * Returns the full canvas
 *
 * @returns {String[][]} - array of all saved pixel color
 */
app.get('/api', async (req, res) => {
    try {
        const result = await pool.query('SELECT * FROM pixels');
        const canvas = Array(50).fill(null).map(() => Array(50).fill('#FFFFFF'));

        result.rows.forEach(row => {
            canvas[row.x][row.y] = row.color;
        });

        res.send(canvas);
    } catch (error) {
        console.error('Error fetching data:', error);
        res.status(500).send('Error fetching data');
    }
});

/**
 * Adds a pixel to the canvas
 *
 * @param {number} x - x-coordinate of the pixel
 * @param {number} y - y-coordinate of the pixel
 * @param {string} color - color in hex format
 */
app.put('/api', async (req, res) => {
    try {
        console.log('Handling Request')

        const x = Math.floor(req.query['x'] / 10);
        const y = Math.floor(req.query['y'] / 10);
        const color = req.body.color;

        if (x >= 0 && x < 50 && y >= 0 && y < 50 && color) {
            await pool.query(
                'INSERT INTO pixels (x, y, color) VALUES ($1, $2, $3) ON CONFLICT (x, y) DO UPDATE SET color = EXCLUDED.color',
                [x, y, color]
            );
            res.status(200).send();
        } else {
            res.status(400).send({ error: 'Invalid coordinates or color' });
        }
    } catch (error) {
        console.error('Error updating data:', error);
        res.status(500).send('Error updating data');
    }
});

// Start server
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
