const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const config = require('../config.json');
const Logger = require('./Logger');
const MySQL = require('../plugin/DataBase/MySQL');

class SERVER {
    constructor() {
        this.app = express();
        this.port = config.port || 3000;
        this.apiDirectory = path.join(__dirname, '../apis'); // API 文件存放目录

        this.logger = new Logger(path.join(__dirname, '../logs/Server.log'), 'INFO');

        // 解析 JSON 请求体
        this.app.use(express.json());

        //解决cors跨域
        this.app.use(cors());

        //使用静态资源
        this.app.use(express.static('./uploads'));

        // 初始化数据库连接
        this.db = new MySQL();

        // 加载 API 路由
        this.loadAPIs(this.apiDirectory);
    }

    // 测试数据库连接
    async initDB() {
        try {
            this.logger.info('正在测试数据库连接');
            await this.db.connect();
            await this.db.close();
        } catch (error) {
            this.logger.error(`数据库连接失败: ${error.stack}`);
            process.exit(1);
        }
    }

    loadAPIs(directory) {
        const items = fs.readdirSync(directory);

        items.forEach(item => {
            const itemPath = path.join(directory, item);
            const stats = fs.statSync(itemPath);

            if (stats.isDirectory()) {
                // 如果是目录，递归调用
                this.loadAPIs(itemPath);
            } else if (stats.isFile() && itemPath.endsWith('.js')) {
                // 如果是文件且是 JavaScript 文件
                this.loadAPIFile(itemPath);
            }
        });
    }

    // 加载单个 API 文件
    loadAPIFile(filePath) {
        try {
            const APIClass = require(filePath);

            for (const key in APIClass) {
                if (APIClass.hasOwnProperty(key)) {
                    const apiInstance = new APIClass[key]();
                    apiInstance.setupRoute();
                    this.app.use('/', apiInstance.getRouter());
                    this.logger.info(`已加载API：${apiInstance.path} 类型：${apiInstance.method}`);
                }
            }
        } catch (error) {
            this.logger.error(`加载API文件失败: ${filePath}，错误: ${error.stack}`);
        }
    }

    start() {
        this.logger.info('============正在启动服务器============');

        // 初始化数据库连接
        this.initDB().then(() => {
            this.app.listen(this.port, () => {
                this.logger.info(`==========服务器正在 ${this.port} 端口上运行==========`);
            });
        }).catch(err => {
            this.logger.error(`启动服务器失败: ${err.message}`);
            process.exit(1); // 启动失败时退出进程
        });
    }
}

module.exports = SERVER;
