package sharin.sql.generator;

public class JoinInfo {

    private final String sourceColumnName;

    private final EntityInfo targetEntityInfo;

    private final String targetTableAlias;

    private final String targetColumnName;

    private final String[] targetColumnAliases;

    public JoinInfo(String sourceColumnName, EntityInfo targetEntityInfo,
            String targetTableAlias) {

        this(sourceColumnName, targetEntityInfo, targetTableAlias,
                targetEntityInfo.getIdColumnName());
    }

    public JoinInfo(String sourceColumnName, EntityInfo targetEntityInfo,
            String targetTableAlias, String targetColumnName) {

        this.sourceColumnName = sourceColumnName;
        this.targetEntityInfo = targetEntityInfo;
        this.targetTableAlias = targetTableAlias;
        this.targetColumnName = targetColumnName;

        String[] propertyNames = targetEntityInfo.getPropertyNames();
        String[] targetColumnAliases = new String[propertyNames.length];

        for (int i = 0; i < propertyNames.length; i++) {
            targetColumnAliases[i] = targetTableAlias + '.' + propertyNames[i];
        }

        this.targetColumnAliases = targetColumnAliases;
    }

    public void appendJoin(StringBuilder builder, String sourceTableAlias) {
        builder.append("LEFT JOIN ");

        String targetTableName = targetEntityInfo.getTableName();
        builder.append(targetTableName);

        if (!targetTableAlias.equals(targetTableName)) {
            builder.append(' ');
            builder.append(targetTableAlias);
        }

        builder.append(" ON ");
        builder.append(sourceTableAlias);
        builder.append('.');
        builder.append(sourceColumnName);
        builder.append(" = ");
        builder.append(targetTableAlias);
        builder.append('.');
        builder.append(targetColumnName);
    }

    public void appendField(StringBuilder builder, String propertyName) {
        builder.append(targetTableAlias);
        builder.append('.');
        builder.append(targetEntityInfo.getColumnName(propertyName));
        builder.append(" AS \"");
        builder.append(targetTableAlias);
        builder.append('.');
        builder.append(propertyName);
        builder.append('"');
    }

    public String[] getTargetColumnAliases() {
        return targetColumnAliases;
    }

    public String getTargetColumnName(String propertyName) {
        return targetTableAlias + '.'
                + targetEntityInfo.getColumnName(propertyName);
    }

    public boolean hasTargetColumnName(String propertyName) {
        return targetEntityInfo.hasColumnName(propertyName);
    }

    public String getTargetTableAlias() {
        return targetTableAlias;
    }
}
