const express = require("express");
const mysql = require("mysql");
const http = require("http");
const fetch = require("isomorphic-fetch");
const bodyParser = require("body-parser");
var cors = require("cors");
const app = express();
const port = process.env.PORT || 8082;
const fs = require("fs");
app.use(cors());

let db;
const createdbConnection = () => {
    db = mysql.createConnection({
        host: "localhost",
        user: "familpps_ashish",
        password: "Ashish@123",
        database: "familpps_ethos_app",
        // host: "localhost",
        // user: "root",
        // password: "",
        // database: "ethos",
    });
};

app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
app.use(express.json());
// createdbConnection()
// const createTableQuery = `
//   CREATE TABLE IF NOT EXISTS user_data (
//     id INT AUTO_INCREMENT PRIMARY KEY,
//     name VARCHAR(255),
//     email VARCHAR(255),
//     title VARCHAR(255),
//     interests VARCHAR(255),
//     qrid VARCHAR(255)
//   )
// `;
// db.query(createTableQuery, (error, results, fields) => {
//     if (error) {
//         throw error;
//     }
//     console.log("Table created successfully");
// });

app.post("/api/save", (req, res) => {
    const data = req.body;
    const { name, title, interest, mail, qrid, finaluri } = data;
    res.setHeader('Access-Control-Allow-Origin', '*');
    createdbConnection();
    db.connect((errdb) => {
        if (errdb) {
            throw errdb;
        } else {
            const filePath = __dirname + `/results/${qrid}.png`;
            const base64Data = finaluri.replace(/^data:image\/png;base64,/, "");
            fs.writeFile(filePath, base64Data, "base64", (err) => {
                if (err) {
                    console.error(err);
                    res.sendStatus(500);
                } else {
                    const sql = `INSERT INTO user_data (name, email, qrid, title,interests) VALUES (?, ?, ?, ?, ?)`;
                    const values = [
                        data.name,
                        data.mail,
                        data.qrid,
                        data.title,
                        data.interest,
                    ];

                    db.query(sql, values, (err, result) => {
                        if (err) {
                            throw err;
                        }
                        // console.log('Data inserted:', result);
                        res.send("Data inserted successfully");
                        db.end();
                    });
                }
            });
        }
    });
});

app.post("/api/upload", (req, res) => {
    const data = req.body;
    const { imageuri, qrid } = data;
    createdbConnection();
    db.connect((errdb) => {
        if (errdb) {
            throw errdb;
        } else {
            const filePath = __dirname + `/canvas/${qrid}.png`;
            // Remove the header from the dataUrl
            const base64Data = imageuri.replace(/^data:image\/png;base64,/, "");
            fs.writeFile(filePath, base64Data, "base64", (err) => {
                if (err) {
                    console.error(err);
                    res.sendStatus(500);
                } else {
                    res.send("Image Uploaded successfully");
                    db.end();
                }
            });
        }
    });
});

app.get("/api/fetchdb", (req, res) => {
    createdbConnection();
    db.connect((errdb) => {
        if (errdb) {
            throw errdb;
        } else {
            const query = "SELECT * FROM user_data";

            db.query(query, (err, result) => {
                if (err) {
                    throw err;
                } else {
                    res.status(200).json(result);
                    db.end();
                }
            });
        }
    });
    
});

app.post("/api/fetchimg", (req, res) => {
    const data = req.body;
    const { qrid } = data;
    const imageUrl = `http://familyindustriesapps.com/Ethos_serve/canvas/${qrid}.png`; // Replace with the actual image URL
    // const imageUrl = __dirname + `/canvas/${qrid}.png`;
    http.get(imageUrl, (response) => {
        const chunks = [];

        response.on("data", (chunk) => {
            chunks.push(chunk);
        });

        response.on("end", () => {
            // Concatenate the image data chunks into a single buffer
            const imageData = Buffer.concat(chunks);

            // Convert the image data to base64
            const base64Image = imageData.toString("base64");

            // Set the response headers
            res.setHeader("Content-Type", "text/plain");
            res.setHeader("Content-Length", Buffer.byteLength(base64Image));
            // Send the base64 image back to the client
            // console.log(base64Image)
            res.end(base64Image);
        });
    }).on("error", (error) => {
        console.error("Error fetching image:", error);
        res.statusCode = 500;
        res.end("Error fetching image");
    });
});

function checkFileStatus(fileUrl) {
    return fetch(fileUrl, { method: "HEAD" })
        .then((response) => response.ok)
        .catch((error) => {
            console.error("Error checking file status:", error);
            return false;
        });
}

app.post("/api/checkimgstatus", (req, res) => {
    const data = req.body;
    const { qrid } = data;
    const imageUrl = `http://familyindustriesapps.com/Ethos_serve/canvas/${qrid}.png`; // Replace with the actual image URL

    checkFileStatus(imageUrl).then((exists) => {
        if (exists) {
            res.statusCode = 200;
            res.end("Image exists");
        } else {
            res.statusCode = 404; // Not Found
            res.end("Image does not exist");
        }
    });
});

app.get("/", (req, res) => {
    res.send("hello, its ethos");
});

app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
});
