const { setSurvey } = require('../connection');

async function get (projectId, path, opts = {}) {
	const client = await setSurvey(projectId);
	const [type, kind, ...jsonpath] = path.split("/");

	const tables = {
		sequences: {
			raw: ["raw_lines", ["sequence"]],
			final: ["final_lines", ["sequence"]],
		},
		points: {
			raw: ["raw_shots", ["sequence", "point"]],
			final: ["final_shots", ["sequence", "point"]],
		},
		lines: {
			preplot: ["preplot_points", ["line", "point"]],
		}
	};

	try {
		const table = tables[kind][type][0];
		const fields = tables[kind][type][1];

		const text = `
			SELECT ${fields.join(", ")}, meta #> $1 AS data
			FROM ${table}
			WHERE meta #> $1 IS NOT NULL
			ORDER BY ${fields.join(", ")};
		`;

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

		return res.rows;
	} catch (err) {
		throw err;
	} finally {
		client.release();
	}
}

module.exports = get;
