package database;

import model.Field;
import model.MLD;
import model.Relation;
import model.ForeignKey;
#if (sys || nodejs)
import sys.io.File;
//~ import sys.db.Postgresql;
import sys.db.Connection;
import sys.db.ResultSet;
#end
using StringTools;

@:expose
class DBPostgreSQL {
	public static function generateSQL(mld : MLD) : String {
		var sql : String = "";
		var sqlrefs : String = "";
		for (r in mld.relations) {
			var hasPK : Bool = false;
			sql += "CREATE TABLE IF NOT EXISTS " + r.name + " (";
			var first : Bool = true;
			for (f in r.fields) {
				var fk : ForeignKey = Lambda.find(r.foreignKeys, fk -> fk.name == f.name);
				first ? first = false : sql += ", ";
				sql += f.name + " ";

				if (f.type.toUpperCase() == "COUNTER") {
					if (r.key.length == 1 && r.key[0] == f.name) { //the counter must be the primary key alone
						sql += "SERIAL PRIMARY KEY";
						hasPK = true;
					} else {
						sql += "INT";
					}
				} else {
					sql += f.dbType;
				}

				if (!hasPK && r.key.length == 1 && r.key[0] == f.name) {
					sql += " PRIMARY KEY";
				}
				if (fk != null) {
					sqlrefs += "ALTER TABLE " + r.name + " ADD FOREIGN KEY (" + f.name + ") REFERENCES " + fk.relation.name + "(" + fk.key + ");\n";
				}
			}
			if (r.key.length != 1) {
				sql += ", PRIMARY KEY(" + r.key.join(",") + ")";
			}
			sql += ");\n";
		}
		sql += sqlrefs;
		return sql;
	}


	#if (sys || nodejs)
	/**
	 * PostrgreSQL is not supported by the standard library.
	 * Haxe library 'npostgres' doesn't support Java nor Python.
	 */
	static function getConnection(paramStr : String) : Connection {
		//~ var params : Array<String> = paramStr.split(",");
		//~ return Postgresql.open('host=${params[0]} dbname=${params[1]} user=${params[2]} password=${params[3]}'); //available on Neko target
		return null; //not implemented
	}

	public static function createDatabase(paramStr : String, sqlFile : String) {
		//not implemented
	}

	public static function analyse(paramStr : String) : MLD {
		return null; //not implemented
	}
	#end
}
