import express from "express";
import fs from "fs";
import ping from "ping";
import path from "path";
import { fileURLToPath } from "url";

const app = express();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

app.use(express.static(path.join(__dirname, "public")));

app.get("/api/status", async (req, res) => {
  try {
    const data = JSON.parse(fs.readFileSync(path.join(__dirname, "devices.json")));
    const promises = data.map(async (device) => {
      try {
        const result = await ping.promise.probe(device.ip, { timeout: 1 });
        return { ...device, status: result.alive ? "on" : "off" };
      } catch {
        return { ...device, status: "off" };
      }
    });
    const results = await Promise.all(promises);
    res.json(results);
  } catch (err) {
    console.error("Gagal membaca devices.json:", err);
    res.status(500).json({ error: "Gagal membaca devices.json" });
  }
});

const PORT = 3000;
app.listen(PORT, () => console.log(`Server berjalan di http://localhost:${PORT}`));
