const { exec } = require('child_process');
var express = require('express')
var path = require('path')

const cmdScreenshot = `adb exec-out screencap -p > temp.png`;
var app = express()

function minicmd(cmd) {
    exec(cmd, (err, stdout, stderr) => {
        if (err) {
            console.error('Error:', err);
            return
        }
    });
}

app.get("/screen.png", (req, res) => {
    // Execute the screenshot command
    exec(cmdScreenshot, (err, stdout, stderr) => {
        if (err) {
            console.error('Error:', err);
            res.send("error")
            return
        }

        // Set cache control headers to prevent caching
        res.set('Cache-Control', 'no-store, no-cache, must-revalidate');
        res.set('Pragma', 'no-cache');
        res.set('Expires', '0');

        // Send the screenshot file
        res.sendFile(path.join(__dirname, "temp.png"));
    });
})

app.get('/', (req, res) => {
    var action = req.query.action || ""
    switch(action) {
        case 'power':
            minicmd(`adb shell input keyevent 26`)
            break;
        case 'back':
            minicmd(`adb shell input keyevent KEYCODE_BACK`)
            break;
    }
    res.sendFile(path.join(__dirname, 'index.html'))
})

app.get('/touch', (req, res) => {
    const x = req.query.x;
    const y = req.query.y;

    if (x !== undefined && y !== undefined) {
        // Convert percentage to screen coordinates
        const width = 540; // Default Android resolution width
        const height = 960; // Default Android resolution height
        const xCoord = (x / 100) * width;
        const yCoord = (y / 100) * height;

        minicmd(`adb shell input tap ${xCoord} ${yCoord}`);
        res.sendStatus(200);
    } else {
        res.sendStatus(400);
    }
})

app.listen(8098)
