const crypt = require("../crypt");

function parseRq (bytes) {
	try {
		return JSON.parse(bytes.toString());
	} catch (e) {
		return undefined;
	}
}

class APIMethods {
	constructor (parent) {
		this.parent = parent;
	}
	
	info (con, req, cb) {
		cb({ result: require("./server-info"), trace_id: req.trace_id, ended: true });
	}
	
	authed (con, req, cb) {
		cb({ result: require("./server-info"), trace_id: req.trace_id, ended: true });
	}
	
	/*setSession (isEncrypted, address, { key, counter }, cb) {
		if (!global.config.server.secureMode)
			return cb({ error: "Encryption is off by configuration file into server" });
		if (!isEncrypted)
			return cb({ error: "Encryption required" });
		try {
			this.parent.sessions[address] = new crypt.AES(key, counter);
			return cb({ result: "Session key installed" });
		} catch (err) {
			return cb({ error: "Invalid params. Must be key and counter" });
		}
	}*/
}

class API {
    constructor () {
		this.methods = new APIMethods(this);
		this.sessions = new WeakMap();
    }
	
	decrypt (address, bytes) {
		throw new Error("Deprecated. Use TLS. If you see this error, please, add issue into: https://git.fullgream.tech/fullgream/ai-adventure-labs/issues");
		/*try {
			if (!global.config.server.secureMode)
				// return Buffer.from([]);
				return undefined;
			if (!this.sessions[address])
				return global.openSSH.decrypt(bytes);
			else
				this.sessions[address].decrypt(bytes);
		} catch (err) {
			return undefined;
		}*/
	}
	
    async exec (connection, bytes, cb) {
		const request = parseRq(bytes);
		
		if (request === undefined)
			return cb({
				error: "required JSON object request"
			});
		
		if (typeof request === "object" && request !== null) {
			const {
				method,
				trace_id
			} = request;
			if (!method)
				return cb({
					error: "method missed"
				});
			if (!trace_id)
				return cb({
					error: "trace_id missed"
				});
			this.methods[method]?.(connection, request, cb);
		} else {
			return cb({
				error: "required JSON-object based request"
			});
		}
    }
}

module.exports = { API };
