const express = require("express");
const app = express();
const http = require('http');
const bodyParser = require("body-parser");
const httpServer = http.Server(app);
const { isOSWindows, defaultWorkingDirectory, setWorkingDirectory, publicDir, FileManager, getCurrentSettings, getWorkingDirectory, validateDirectory } = require('./fileManager');

module.exports = run

function run() {
	var port = 3202;
	httpServer.listen(port);

	app.use(bodyParser.json());
	app.use(bodyParser.urlencoded({ limit: '500mb', extended: true }));

	app.get("/get-add-in-info", async function (req, res) {
		res.status(200).send({ os: { isOSWindows, publicDir, homeDir: getWorkingDirectory() }, extensionVersion: "1.0.6" });
	});

	app.post("/download-resources", async function (req, res) {
		try {
			const data = req.body;
			const fileManager = new FileManager(data);
			const deleteStatus = await fileManager.checkDirsAndDeleteHomeFiles();

			let templates = [];
			let resources = [];

			if (deleteStatus.ok === true) {
				templates = await fileManager.processFiles(fileManager.publicDirInfo.startersLangDir, fileManager.homeDirInfo.startersDir, data.templates);
				resources = await fileManager.processFiles(fileManager.publicDirInfo.resourcesDir, fileManager.homeDirInfo.resourcesDir, data.resources);
			}
			else {
				res.status(200).send(deleteStatus);
				return;
			}

			res.status(200).send({ ok: true, publicDirInfo: fileManager.publicDirInfo, homeDirInfo: fileManager.homeDirInfo, templates, resources });
		} catch (error) {
			res.status(200).send({ ok: false, errorMessage: error.message });
		}
	});

	app.post("/update-working-directory", async function (req, res) {
		try {
			const workingDirectory = req.body.workingDirectory;
			try {
				validateDirectory(workingDirectory);
			} catch (error) {
				res.status(200).send({ ok: false, errorMessage: error.message });
				return;
			}
			const settings = getCurrentSettings();
			settings.workingDirectory = workingDirectory;

			setWorkingDirectory(settings);

			res.status(200).send({ ok: true, workingDirectory: workingDirectory });
		} catch (error) {
			res.status(500).send({ ok: false, errorMessage: error.message });
		}
	});

	app.post("/reset-working-directory", async function (req, res) {
		try {
			const settings = getCurrentSettings();
			settings.workingDirectory = defaultWorkingDirectory;

			setWorkingDirectory(settings);

			res.status(200).send({ ok: true, workingDirectory: defaultWorkingDirectory });
		} catch (error) {
			res.status(500).send({ ok: false, errorMessage: error.message });
		}
	});

	app.get("/get-working-directory", async function (req, res) {
		try {
			const workingDirectory = getWorkingDirectory();
			res.status(200).send({ ok: true, workingDirectory });
		} catch (error) {
			res.status(500).send({ ok: false, errorMessage: error.message });
		}
	});

	app.get('/identity-provider/callback', async function (req, res, next) {
		try {
			const csInterface = new CSInterface();
			const extensionId = csInterface.getExtensionID();
			const event = new CSEvent(`cep.${extensionId}.event.message`, "APPLICATION");
			const state = req.query.state;

			event.data = JSON.stringify({ state });
			event.extensionId = extensionId

			csInterface.dispatchEvent(event);

			res.setHeader("Content-Type", "text/html")
			res.status(200).send(
				`
				<html>
					<body>
						<div style="display: flex;	flex-direction: column;	align-items: center;">
							<img src="https://learning.isograd.com/static/media/tosa_logo.e999465b.svg" width="350" />
							<span style="font-size: larger;">You can close this tab and continue in the Adobe application.</span>
						<div>
					</body>
				</html>
				`
			);
		} catch (error) {
			next(error);
		}
	});
}
