package model;

class Relation extends Obj {
	public var key : Array<String>;
	public var foreignKeys : Array<ForeignKey>;

	public function new(name : String) {
		super(name);
		this.key = new Array();
		this.foreignKeys = new Array();
	}

	public function mergeForeignKeys() : Array<MergedFK> {
		var mergedFKList : Array<MergedFK> = new Array();
		var i : Int = 0;
		while (i < foreignKeys.length) {
			var currentFK : MergedFK = { names : [ foreignKeys[i].name ], relation : foreignKeys[i].relation, keys : [ foreignKeys[i].key ] };
			for (j in 1...currentFK.relation.key.length) {
				currentFK.names.push(foreignKeys[i + j].name);
				currentFK.keys.push(foreignKeys[i + j].key);
				i++;
			}
			i++;
			mergedFKList.push(currentFK);
		}
		return mergedFKList;
	}

	public function toENString() : String {
		return name + " (" + fields.map(f -> f.name).join(", ") + ")\n" +
			"    clé primaire : " + key.join(", ") + (foreignKeys.length == 0 ? "" : "\n") +
			//~ foreignKeys.map(fk -> "    clé étrangère : " + fk.name + " référence " + fk.relation.name + "(" + fk.key + ")").join("\n") + "\n";
			mergeForeignKeys().map(mfk -> "    clé étrangère : " + mfk.names.join(", ") +
					" référence " + mfk.relation.name + "(" + mfk.keys.join(", ") + ")").join("\n") + "\n";
	}

	public function toUnivString() : String {
		var strings : Array<String> = new Array();
		for (k in key) {
			strings.push("\x1B[4m" + (Lambda.map(foreignKeys, fk -> fk.name).indexOf(k) == -1 ? "" : "#") + k + "\x1B[0m");
		}
		for (f in fields) {
			if (key.indexOf(f.name) == -1) {
				strings.push((Lambda.map(foreignKeys, fk -> fk.name).indexOf(f.name) == -1 ? "" : "#") + f.name);
			}
		}
		return "\x1B[1m" + name  + "\x1B[0m (" + strings.join(", ") + ")\n";
	}
}
