// Copyright (c) 2015, JINGROW and Contributors
// MIT License. See license.txt

jingrow.db = {
	get_list: function (pagetype, args) {
		if (!args) {
			args = {};
		}
		args.pagetype = pagetype;
		if (!args.fields) {
			args.fields = ["name"];
		}
		if (!("limit" in args)) {
			args.limit = 20;
		}
		return new Promise((resolve) => {
			jingrow.call({
				method: "jingrow.desk.reportview.get_list",
				args: args,
				type: "GET",
				callback: function (r) {
					resolve(r.message);
				},
			});
		});
	},
	exists: function (pagetype, name) {
		return new Promise((resolve) => {
			jingrow.db.get_value(pagetype, { name: name }, "name").then((r) => {
				r.message && r.message.name ? resolve(true) : resolve(false);
			});
		});
	},
	get_value: function (pagetype, filters, fieldname, callback, parent_pg) {
		return jingrow.call({
			method: "jingrow.client.get_value",
			type: "GET",
			args: {
				pagetype: pagetype,
				fieldname: fieldname,
				filters: filters,
				parent: parent_pg,
			},
			callback: function (r) {
				callback && callback(r.message);
			},
		});
	},
	get_single_value: (pagetype, field) => {
		return new Promise((resolve) => {
			jingrow
				.call({
					method: "jingrow.client.get_single_value",
					args: { pagetype, field },
					type: "GET",
				})
				.then((r) => resolve(r ? r.message : null));
		});
	},
	set_value: function (pagetype, pagename, fieldname, value, callback) {
		return jingrow.call({
			method: "jingrow.client.set_value",
			args: {
				pagetype: pagetype,
				name: pagename,
				fieldname: fieldname,
				value: value,
			},
			callback: function (r) {
				callback && callback(r.message);
			},
		});
	},
	get_pg: function (pagetype, name, filters) {
		return new Promise((resolve, reject) => {
			jingrow
				.call({
					method: "jingrow.client.get",
					type: "GET",
					args: { pagetype, name, filters },
					callback: (r) => {
						jingrow.model.sync(r.message);
						resolve(r.message);
					},
				})
				.fail(reject);
		});
	},
	insert: function (pg) {
		return jingrow.xcall("jingrow.client.insert", { pg });
	},
	delete_pg: function (pagetype, name) {
		return new Promise((resolve) => {
			jingrow.call("jingrow.client.delete", { pagetype, name }, (r) => resolve(r.message));
		});
	},
	count: function (pagetype, args = {}) {
		let filters = args.filters || {};
		let limit = args.limit;

		// has a filter with childtable?
		const distinct =
			Array.isArray(filters) &&
			filters.some((filter) => {
				return filter[0] !== pagetype;
			});

		const fields = [];

		return jingrow.xcall("jingrow.desk.reportview.get_count", {
			pagetype,
			filters,
			fields,
			distinct,
			limit,
		});
	},
	get_link_options(pagetype, txt = "", filters = {}) {
		return new Promise((resolve) => {
			jingrow.call({
				type: "GET",
				method: "jingrow.desk.search.search_link",
				args: {
					pagetype,
					txt,
					filters,
				},
				callback(r) {
					resolve(r.message);
				},
			});
		});
	},
};
