const { setSurvey } = require('../connection');
const checkPermission = require('./check-permission');

async function get (projectId, path, opts = {}, operations = []) {
	const client = await setSurvey(projectId);
	const [key, ...subkey] = path.split("/").filter(i => i.trim().length);

	if (!checkPermission(key, "get", operations)) {
		throw {status: 403, message: "Forbidden"};
		return;
	}

	const text = `
		SELECT value
		FROM info
		WHERE key = $1;
	`;

	const res = await client.query(text, [key]);
	client.release();

	const value = res.rows[0] && res.rows[0].value;

	if (subkey.length) {
		const res = subkey.reduce( (obj, idx) => typeof obj != "undefined" ? obj[idx] : obj, value);
		//console.log(res);
		return res;
	} else {
		return value;
	}
}

module.exports = get;
