"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
const _express = /*#__PURE__*/ _interop_require_default(require("express"));
const _nodehttp = /*#__PURE__*/ _interop_require_default(require("node:http"));
const _nodefs = /*#__PURE__*/ _interop_require_default(require("node:fs"));
const _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
const _defaultimage = require("./default-image.js");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const port = process.argv[2] ? Number.parseInt(process.argv[2]) : 8181;
const fps = process.argv[3] ? Number.parseInt(process.argv[3]) : 10;
const frameInterval = 1000 / fps;
const app = (0, _express.default)();
const server = _nodehttp.default.createServer(app);
const activeIntervals = new Set();
const framesDir = _nodepath.default.join(process.cwd(), "media", "mock-camera");
if (!_nodefs.default.existsSync(framesDir)) {
    console.log(`[CAMERA:${port}] Creating frames folder ${framesDir}`);
    console.log(`[CAMERA:${port}] You can place custom .jpg/.jpeg/.png images here to use as frames`);
    _nodefs.default.mkdirSync(framesDir, {
        recursive: true
    });
}
let customFrames = [];
try {
    const files = _nodefs.default.readdirSync(framesDir).filter((f)=>{
        const lower = f.toLowerCase();
        return lower.endsWith('.jpg') || lower.endsWith('.jpeg') || lower.endsWith('.png');
    }).sort((a, b)=>a.localeCompare(b));
    if (files.length > 0) {
        console.log(`[CAMERA:${port}] Loading ${files.length} custom frame(s) from ${framesDir}`);
        customFrames = files.map((f)=>{
            const filePath = _nodepath.default.join(framesDir, f);
            const data = _nodefs.default.readFileSync(filePath);
            const contentType = f.toLowerCase().endsWith('.png') ? 'image/png' : 'image/jpeg';
            return {
                data,
                contentType
            };
        });
        console.log(`[CAMERA:${port}] Loaded custom frames: ${files.join(', ')}`);
    }
} catch (error) {
    console.error(`[CAMERA:${port}] Error loading custom frames:`, error);
}
const defaultFrame = {
    data: Buffer.from(_defaultimage.DEFAULT_IMAGE_BASE64, 'base64'),
    contentType: 'image/jpeg'
};
console.log(`[CAMERA:${port}] Loaded default frame from embedded image`);
function generateFrame() {
    if (customFrames.length > 0) {
        const frameIndex = Math.floor(Date.now() / 1000) % customFrames.length;
        return customFrames[frameIndex];
    }
    return defaultFrame;
}
app.get("/", (req, res)=>{
    console.log(`[CAMERA:${port}] New MJPEG stream connection from ${req.ip}`);
    res.writeHead(200, {
        'Content-Type': 'multipart/x-mixed-replace; boundary=--FRAME',
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0',
        'Connection': 'close'
    });
    const intervalId = setInterval(()=>{
        try {
            const frame = generateFrame();
            res.write('--FRAME\r\n');
            res.write(`Content-Type: ${frame.contentType}\r\n`);
            res.write(`Content-Length: ${frame.data.length}\r\n`);
            res.write('\r\n');
            res.write(frame.data);
            res.write('\r\n');
        } catch (error) {
            console.error(`[CAMERA:${port}] Error sending frame:`, error);
            clearInterval(intervalId);
            activeIntervals.delete(intervalId);
            res.end();
        }
    }, frameInterval);
    activeIntervals.add(intervalId);
    req.on('close', ()=>{
        console.log(`[CAMERA:${port}] Client disconnected`);
        clearInterval(intervalId);
        activeIntervals.delete(intervalId);
    });
    res.on('error', (error)=>{
        console.error(`[CAMERA:${port}] Response error:`, error);
        clearInterval(intervalId);
        activeIntervals.delete(intervalId);
    });
});
app.get("/snapshot", (req, res)=>{
    console.log(`[CAMERA:${port}] Snapshot request from ${req.ip}`);
    try {
        const frame = generateFrame();
        res.writeHead(200, {
            'Content-Type': frame.contentType,
            'Content-Length': frame.data.length,
            'Cache-Control': 'no-cache'
        });
        res.end(frame.data);
    } catch (error) {
        console.error(`[CAMERA:${port}] Error generating snapshot:`, error);
        res.status(500).json({
            error: 'Failed to generate snapshot'
        });
    }
});
app.get("/status", (req, res)=>{
    res.json({
        status: 'online',
        fps: fps,
        customFrames: customFrames.length,
        framesDir: framesDir
    });
});
app.use((req, res)=>{
    console.log(`[CAMERA:${port}] ${req.method.toUpperCase()} ${req.url} Not found`);
    res.status(404).json({
        error: 'Not Found'
    });
});
server.listen(port, ()=>{
    console.log(`[CAMERA:${port}] Mock camera server running on http://localhost:${port}`);
    console.log(`[CAMERA:${port}] MJPEG stream: http://localhost:${port}/`);
    console.log(`[CAMERA:${port}] Snapshot: http://localhost:${port}/snapshot`);
    console.log(`[CAMERA:${port}] Status: http://localhost:${port}/status`);
    console.log(`[CAMERA:${port}] FPS: ${fps}`);
    const framesString = customFrames.length > 0 ? `${customFrames.length} loaded` : 'none (using placeholder)';
    console.log(`[CAMERA:${port}] Custom frames: ${framesString}`);
    if (customFrames.length === 0) {
        console.log(`[CAMERA:${port}] Tip: Add .jpg or .png files to ${framesDir} to use custom frames`);
    }
});
function shutdown(signal) {
    console.log(`\n[CAMERA:${port}] Received ${signal} signal. Shutting down gracefully...`);
    console.log(`[CAMERA:${port}] Clearing ${activeIntervals.size} active stream(s)...`);
    activeIntervals.forEach((interval)=>clearInterval(interval));
    activeIntervals.clear();
    server.close(()=>{
        console.log(`[CAMERA:${port}] Server closed`);
        process.exit(0);
    });
    setTimeout(()=>{
        console.error(`[CAMERA:${port}] Could not close connections in time, forcefully shutting down`);
        process.exit(1);
    }, 5000);
}
process.on('SIGINT', ()=>shutdown('SIGINT'));
process.on('SIGTERM', ()=>shutdown('SIGTERM'));

//# sourceMappingURL=mock-camera.server.js.map