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

async function post (projectId, payload, opts = {}) {

	const client = await setSurvey(projectId);
	try {

		if (!payload.sequence) {
			payload.sequence = await lib.getSequence(client);
		}
		if (!payload.ts0 || !payload.ts1) {
			const ts = await lib.getTimestamps(client, projectId, payload);
			if (!payload.ts0) {
				payload.ts0 = ts.ts0;
			}
			if (!payload.ts1) {
				payload.ts1 = ts.ts1;
			}
		}
		if (!payload.name) {
			payload.name = await lib.getLineName(client, projectId, payload);
		}

		const p = Object.assign({
			remarks: "",
			meta: {}
		}, payload);

		const text = `
			INSERT
			INTO planned_lines (sequence, line, fsp, lsp, ts0, ts1, name, remarks, meta)
			VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
		`;
		const values = [ p.sequence, p.line, p.fsp, p.lsp, p.ts0, p.ts1, p.name, p.remarks, p.meta ];

		await client.query(text, values);
	} catch (err) {
		if (err.code && Math.trunc(err.code/1000) == 23) {
			// Class 23 — Integrity Constraint Violation
			console.error(err);
			throw { status: 400, message: "Malformed request" };
		} else {
			throw err;
		}
	} finally {
		client.release();
	}

	return;
}

module.exports = post;
