// create express app
const express = require('express');
const cors = require('cors');
const fileUpload = require('express-fileupload');
const dotenv = require('dotenv');
const path = require('path');
const conn = require('./conn');
const connection = conn.connection;
const app = express();


dotenv.config();

app.use(express.static(path.join(__dirname, 'assets')));

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
// console.log(__dirname);

app.get('/', (req, res) => {
    // this is the default route
    console.log("buka halaman utama");
    res.sendFile(__dirname + '/ui/index.html');

})

// below is the route for the data
app.get('/data', async (req, res) => {
    const { id, wifi, internet } = req.query;
    console.log(id, wifi, internet);

    const query = 'SELECT * FROM tb_ont';
    connection.query(query, (err, result) => {
        if (err) {
            console.log(err, "error menerima data");
            return res.status(500).send('Internal Server Error');
        }

        if (result.length === 0) {
            console.log('Data not found');
            return res.status(404).send('Data not found');
        }

        const statusnya = wifi == "disconnected" && internet == "disconnected" ? "Tidak Terhubung Ke Wifi" : wifi == "connected" && internet == "disconnected" ? "Wifi Terhubung, Tidak Terhubung Ke Internet" : wifi == "connected" && internet == "connected" ? "Terhubung ke Wifi dan Internet" : "Tidak Terhubung";

        console.log(statusnya);
        // Create a Date object
        let now = new Date();

        // Convert the time to UTC+8
        let datetime = new Date(now.getTime());

        
        console.log(datetime);


        const query_update = 'UPDATE tb_ont SET status = ? , updated = ? WHERE id = ?';


        connection.query(query_update, [statusnya, datetime, id], (err, result) => {
            if (err) {
                console.log(err, "error menerima data");
                return res.status(500).send('Internal Server Error');
            }
            console.log("data berhasil diupdate");
            return res.status(200).send('Data updated successfully');
        });
    })
    // get the id,wifi,internet parameter

    // res.send({ id, wifi, internet });
});


// error handler
app.use((err, req, res, next) => {
    // this is the error handler
    console.error(err.stack);
    res.status(500).send('Something broke!');

})

// below is the route for the admin
app.use('/admin', require('./routes/admin_route'));


// below is port 
const port = process.env.PORT || 3010;

app.listen(port, () => {
    // server started
    console.log(`Server running on port ${port}`);
})
