const opc = require("../../index.js");
const app = require("express")();

const FOLDER_PATH = "./images";

app.use((req, res, next) => {
	//return next();  // <-- Disable All CORS rules
	res.setHeader("Access-Control-Allow-Origin", "*");
	res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
	res.setHeader("Access-Control-Allow-Headers", "Content-Type");

	if (req.method === "OPTIONS") {
		return res.sendStatus(200);
	}

	next();
});
app.use(require("body-parser").json());

const tasks = new Object();
async function generateTask (id) {
	const task = await opc.generateTask(FOLDER_PATH);
	tasks[id] = {
		answer: task.answer,
		successCode: task.openPuzzleCaptchaAPI.taskSolved.successCode,
		fragments: task.openPuzzleCaptchaAPI.getTask.fragments,
	};
}

function generateTaskId () {
	return Buffer.from([...new Array(4)]
		.map(() => Math.round(Math.random() * 255)))
		.toString('hex');
}

app.get("/:taskId", async (req, res) => {
	const taskId = req.params.taskId;
	
	// For DEMO
	if (!tasks[taskId] && taskId === "test")
		await generateTask("test");
	
	if (!tasks[taskId]) return res.status(400).json({
		isError: true,
		message: `Unknown task: ${req.params.taskId}`,
	});
	
	if (tasks[taskId] === true)
		await generateTask(taskId);
	
	return res.json({
		isError: false,
		mode: "3x3",
		fragments: tasks[taskId].fragments,
	});
});

app.post("/:taskId", async (req, res) => {
	const taskId = req.params.taskId;
	if (!tasks[taskId]) return res.status(400).json({
		isError: true,
		message: `Unknown task: ${req.params.taskId}`,
	});
	
	if (!req.body.answer) return res.status(400).json({
		isError: true,
		message: "Filed 'answer' not found in JSON body",
	});
	
	const answer = req.body.answer;
	const trueAnswer = tasks[taskId].answer;
	const successCode = tasks[taskId].successCode;
	
	delete tasks[taskId];
	
	if (answer !== trueAnswer) {
		const tryAgain = generateTaskId();
		tasks[tryAgain] = true;
		
		return res.json({
			isError: false,
			isSuccess: false,
			tryAgain: "/"+tryAgain,
		});
	}
	return res.json({
		isError: false,
		isSuccess: true,
		successCode,
	});
});

app.listen(8081, async (err) => {
	if (err) throw err;
	generateTask("test");
	console.log("Listen 8081");
});
