/*
 * The MIT License
 *
 * Copyright 2021 steve.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package slite.lib_java;

import java.util.HashMap;

/**
 *
 * @author steve
 */
public class LIBSys
{
	DbCockroach db;

	public LIBSys(DbCockroach db)
	{
		this.db = db;
	}

	public DbRows getLinked(String tableToGet, String linkedToTable, String linkedToId, HashMap<String, String> options)
	{
		
		var type = "link";
		var where = "";
		var order = "";

		var tableToGetF = this.db.quoteField(tableToGet);
		var tableToGetV = this.db.quoteValue(tableToGet);
		var linkedToTableV = this.db.quoteValue(linkedToTable);
		var linkedToIdV = this.db.quoteValue(linkedToId);

		var select = tableToGetF+"*";
		
		if(options!=null)
		{
			var tmp = "";
			
			tmp = options.get("select");
			if(tmp!=null) select = tmp;

			tmp = options.get("where");
			if(tmp!=null) where = tmp;

			tmp = options.get("order");
			if(tmp!=null) order = tmp;

			tmp = options.get("type");
			if(tmp!=null) type = tmp;
		}

		var typeV = this.db.quoteValue(type);

		
		var a = "a";
		var b = "b";
		
		int cmp = linkedToTable.compareTo(tableToGet);
		if(cmp > 0)
		{
			a = "b";
			b = "a";
		}
		
		var sql = ""
				+ " SELECT"
				+ " "+select
				+ " FROM"
				+ " sys_link"
				+ " INNER JOIN"
				+ " "+tableToGetF
				+ " ON"
				+ " sys_link."+b+"_id = "+tableToGetF+".id"
				+ " WHERE"
				+ " sys_link."+a+"_table = "+linkedToTableV
				+ " AND"
				+ " sys_link."+a+"_id = "+linkedToIdV
				+ " AND"
				+ " sys_link."+b+"_table = "+tableToGetV
				+ (!type.equals("*") ? " AND sys_link.type = "+typeV : "")
				+ "";
		
		if(!where.isEmpty()) sql += " AND ("+where+")";
		if(!order.isEmpty()) sql += " ORDER BY "+order;
		
		System.out.println(sql);
		
		return this.db.get(sql);
	}
}
