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

async function getSummary (projectId, line, opts = {}) {
	const client = await setSurvey(projectId);

	const text = `
		SELECT pls.line, pls.fsp, pls.lsp, pls.num_points, pls.length, pls.azimuth, pls.incr,
		pl.ntba, pl.geometry, pl.remarks, pl.meta
		FROM preplot_lines_summary pls
		INNER JOIN preplot_lines pl
			ON psl.line = pl.line and pl.class = 'V'
		WHERE ($1:integer IS NULL) OR (line = $1);
	`;

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

	return res.rows[0];
}


async function get (projectId, type = "sail", line = null, opts = {}) {
	if (opts.summary) {
		return await getSummary(projectId, line, opts);
	}

	const client = await setSurvey(projectId);

	const sortFields = [
		"sailline", "line", "point", "ntba", "sailline_ntba"
	];
	const sortKey = opts.sortBy && sortFields.includes(opts.sortBy) && opts.sortBy || "line";
	const sortDir = opts.sortDesc == "false" ? "ASC" : "DESC";
	const offset = Math.abs(opts.offset) || Math.abs((opts.page-1)*opts.itemsPerPage) || 0;
	const limit = Math.abs(opts.limit) || Math.abs(Number(opts.itemsPerPage)) || null;

	let res;

	if (type == "source") {

		const geometry = (opts.wgs84 || opts.lonlat || opts.latlon)
			? "ST_Transform(geometry, 4326)::json geometry"
			: "geometry::json";

		const restriction = line
			? "(sailline = $3 OR line = $3)"
			: "(TRUE OR $3)";

		const text = `
			SELECT
				sailline, sailline_ntba, line, point, ntba,
				${geometry},
				meta
			FROM preplot_saillines_points
			WHERE ${restriction}
			ORDER BY ${sortKey} ${sortDir}
			OFFSET $1
			LIMIT $2;
		`;

		const values = [offset, limit, line];
		res = await client.query(text, values);

	} else if (type == "sail") {

		const geometry = (opts.wgs84 || opts.lonlat || opts.latlon)
			? "ST_Transform(pp.geometry, 4326)::json geometry"
			: "pp.geometry::json";

		const restriction = line
			? "(sailline = $3 OR psl.line = $3)"
			: "(TRUE OR $3)";

		const text = `
			WITH psl AS (
				SELECT DISTINCT sailline, ntba
				FROM preplot_saillines
			)
			SELECT
				psl.sailline, pp.point, pp.ntba, psl.ntba sailline_ntba, pp.meta, ${geometry}
			FROM preplot_points pp
				INNER JOIN psl ON psl.sailline = pp.line
			WHERE pp.class = 'V'
				AND ${restriction}
			ORDER BY ${sortKey} ${sortDir}
			OFFSET $1
			LIMIT $2;
		`;

		const values = [offset, limit, line];
		res = await client.query(text, values);

	}

	client.release();

	if (opts.project) {
		const tokens = opts.project.split(/\s*[,;:\s]\s*/).filter(e => e.length);
		const project = tokens.map(i => i.replace(/^([^.]+)\..*$/, "$1"));
		return res.rows.map( r =>
			Object.fromEntries(Object.entries(r).filter(entry => project.includes(entry[0])))
		);
	} else {
		return res.rows;
	}
}

module.exports = get;
