package org.peekmoon.database.walker.schema;

import java.util.ArrayList;
import java.util.List;

public class Key {
	
	private final String name;
	private final Table table;
	private final List<Integer> columnIdxs;
	
	public Key(String name, Table table) {
		this.name = name;
		this.table = table;
		this.columnIdxs = new ArrayList<>();
	}
	
	public void addColumn(String columnName) {
		Integer columnIdx = table.getColumnIdx(columnName);
		columnIdxs.add(columnIdx);
	}

	public Table getTable() {
		return table;
	}
	
	public Schema getSchema() {
		return table.getSchema();
	}
	
	public boolean isName(String keyName) {
		return this.name.equals(keyName);
	}
	
	public String getSqlSelect() {
		return table.getSqlSelect() + getSqlWhere();
	}
	
	public String getSqlWhere() {
		StringBuilder sb = new StringBuilder(" WHERE 1=1 ");
		for (int columnIdx : columnIdxs) {
			sb.append(" AND ").append(table.getColumnName(columnIdx)).append(" = ?");
		}
		return sb.toString();
	}
	
	public List<Integer> getColumnIdxs() {
		return columnIdxs;
	}
	
	public boolean contains(int i) {
		return columnIdxs.contains(i);
	}

	@Override
	public String toString() {
		return "Key [name=" + name + ", table=" + table.getName() + ", columnIdxs=" + columnIdxs + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Key other = (Key) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	

}

@@ -89,16 +89,52 @@
 il.List;
+%0Aimport java.util.stream.Collectors;
 %0A%0Apublic
@@ -146,18 +146,17 @@
 s Key %7B%0A
-%09
 %0A
+
 %09private
@@ -244,18 +244,17 @@
 mnIdxs;%0A
-%09
 %0A
+
 %09public 
@@ -365,26 +365,25 @@
 ist%3C%3E();%0A%09%7D%0A
-%09
 %0A
+
 %09public void
@@ -543,26 +543,25 @@
 n table;%0A%09%7D%0A
-%09
 %0A
+
 %09public Sche
@@ -604,26 +604,25 @@
 chema();%0A%09%7D%0A
-%09
 %0A
+
 %09public bool
@@ -685,26 +685,25 @@
 eyName);%0A%09%7D%0A
-%09
 %0A
+
 %09public Stri
@@ -768,26 +768,25 @@
 Where();%0A%09%7D%0A
-%09
 %0A
+
 %09public Stri
@@ -1000,26 +1000,25 @@
 tring();%0A%09%7D%0A
-%09
 %0A
+
 %09public List
@@ -1069,17 +1069,155 @@
 dxs;%0A%09%7D%0A
-%09
+%0A%09public List%3CString%3E getColumnNames() %7B%0A%09%09return columnIdxs.stream()%0A%09%09%09%09.map(table::getColumnName)%0A%09%09%09%09.collect(Collectors.toList());%0A%09%7D%0A
 %0A%09public
@@ -1930,11 +1930,9 @@
 %0A%09%7D%0A
-%09%0A%09
+%0A
 %0A%0A%7D%0A

Add method returning all column names referencing a key