package common.db.dao.hibernate.reveng;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.hibernate.cfg.reveng.DelegatingReverseEngineeringStrategy;
import org.hibernate.cfg.reveng.ReverseEngineeringStrategy;
import org.hibernate.cfg.reveng.TableIdentifier;

public final class DefaultStrategy extends DelegatingReverseEngineeringStrategy {

	private final Map<String, Set<String>> tables = new HashMap<>();

	public DefaultStrategy(final ReverseEngineeringStrategy delegate) {
		super(delegate);
	}

	@Override
	public boolean excludeColumn(final TableIdentifier identifier, final String columnName) {
		Set<String> columns = this.tables.computeIfAbsent(identifier.getName(), k -> new HashSet<>());
		columns.add(columnName);
		return super.excludeColumn(identifier, columnName);
	}

	@Override
	public String getTableIdentifierStrategyName(final TableIdentifier identifier) {
		Set<String> columns = this.tables.get(identifier.getName());
		if (columns != null) {
			if (columns.contains("ID") || columns.contains("id")) {
				return "sequence";
			}
		}
		return null;
	}

	@Override
	public Properties getTableIdentifierProperties(final TableIdentifier identifier) {
		Properties params = new Properties();
		String name = identifier.getName();
		Set<String> columns = this.tables.get(name);
		if (columns != null) {
			if (columns.contains("ID") || columns.contains("id")) {
				if (name.startsWith("ms_") || name.startsWith("MS_")) {
					params.put("sequence", "sq_master");
				} else if (name.startsWith("tr_") || name.startsWith("TR_")) {
					params.put("sequence", "sq_transaction");
				}
			}
		}
		return params;
	}

	@Override
	public List<String> getPrimaryKeyColumnNames(final TableIdentifier identifier) {
		List<String> list = new ArrayList<>();
		list.add("ID");
		return list;
	}

	@Override
	public String tableToIdentifierPropertyName(final TableIdentifier identifier) {
		return null;
	}

	@Override
	public String tableToCompositeIdName(final TableIdentifier identifier) {
		return null;
	}
}
