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

async function put (projectId, payload, opts = {}) {
	const client = await setSurvey(projectId);
// 	const [type, ...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 {

		if (!Array.isArray(payload)) {
			payload = [payload];
		}

		transaction.begin(client);
		for (const rec of payload) {
			const type = rec.type || "raw";
			if (rec.point && rec.sequence) {
				const table = tables.points[type][0]
				const text = `
					UPDATE ${table}
					SET meta = jsonb_set(meta, $1, $2)
					WHERE sequence = $3 AND point = $4;
				`
				const values = [ rec.path, JSON.stringify(rec.value), rec.sequence, rec.point ];

				await client.query(text, values);
			} else if (rec.sequence) {
				const table = tables.sequences[type][0]
				const text = `
					UPDATE ${table}
					SET meta = jsonb_set(meta, $1, $2)
					WHERE sequence = $3;
				`
				const values = [ rec.path, JSON.stringify(rec.value), rec.sequence ];

				await client.query(text, values);
			} else if (rec.point && rec.line) {
				const table = tables.lines[type][0]
				const text = `
					UPDATE ${table}
					SET meta = jsonb_set(meta, $1, $2)
					WHERE line = $3 AND point = $4;
				`
				const values = [ rec.path, JSON.stringify(rec.value), rec.line, rec.point ];

				await client.query(text, values);
			} else {
				// Ignore, but report
				console.error("I do not know where to store this meta", record);
			}
		}
		transaction.commit(client);

	} catch (err) {
		console.error("ERROR", err);
		transaction.rollback(client);
		throw err;
	} finally {
		client.release();
	}
}

module.exports = put;
