import express from "express";
import * as os from "os";
import config from "../config.js";
import { NetworkInterfaceDetails } from "types/types";

// バックエンドルーティング
import CommandExecute from "./route/command.js";
import ueusePost from "./route/ueuse.js";
import WeatherUeuse from "./route/weather.js";
import API from "./route/api.js";
import Token from "./route/token.js";
import Debug from "./route/debug.js";

export default async function AdminPanel() {
  // 無効
  if (!config.admin.panel.isEnabled) {
    return;
  }

  // 管理パネル
  const app = express();
  const port = config.admin.panel.port;

  // ルーティング
  app.use(ueusePost);
  app.use(CommandExecute);
  app.use(WeatherUeuse);
  app.use(API);
  app.use(Token);
  app.use(Debug);
  app.use(express.static("panel/public"));

  app.listen(port, () => {
    console.log(`http://${LocalIP()}:${port} で管理パネルを起動しました`);
  });
}

function LocalIP() {
  const interfaces = os.networkInterfaces();

  for (const name in interfaces) {
    const iface: any = interfaces[name];

    for (const i of iface) {
      const details: NetworkInterfaceDetails = i;

      if (details.family === 'IPv4' && details.internal !== true) {
        return details.address;
      }
    }
  }

  return "localhost";
}
