package com.uas.report.crystal2jasper;

import java.util.List;

/**
 * 表之间的join
 * 
 * @author sunyj
 * @since 2017年5月23日 下午2:03:37
 */
public class Join {

	private String fromTableName;
	private String fromTableAlias;
	private String toTableName;
	private String toTableAlias;
	private JoinType joinType;
	private List<Link> links;

	public Join(String fromTableAlias, String toTableAlias, JoinType joinType) {
		this.fromTableAlias = fromTableAlias;
		this.toTableAlias = toTableAlias;
		this.joinType = joinType;
	}

	public String getFromTableName() {
		return fromTableName;
	}

	public void setFromTableName(String fromTableName) {
		this.fromTableName = fromTableName;
	}

	public String getFromTableAlias() {
		return fromTableAlias;
	}

	public void setFromTableAlias(String fromTableAlias) {
		this.fromTableAlias = fromTableAlias;
	}

	public String getToTableName() {
		return toTableName;
	}

	public void setToTableName(String toTableName) {
		this.toTableName = toTableName;
	}

	public String getToTableAlias() {
		return toTableAlias;
	}

	public void setToTableAlias(String toTableAlias) {
		this.toTableAlias = toTableAlias;
	}

	public JoinType getJoinType() {
		return joinType;
	}

	public void setJoinType(JoinType joinType) {
		this.joinType = joinType;
	}

	public List<Link> getLinks() {
		return links;
	}

	public void setLinks(List<Link> links) {
		this.links = links;
	}

	public String getExpression() {
		StringBuilder builder = new StringBuilder(joinType.getExpression());
		builder.append(" ").append(toTableName);
		if (!toTableName.equals(toTableAlias)) {
			builder.append(" ").append(toTableAlias);
		}
		builder.append(" ON ");
		int i = 0;
		for (Link link : links) {
			if (i++ != 0) {
				builder.append(" and ");
			}
			builder.append(fromTableAlias).append(".").append(link.getFromColumnName()).append(" ")
					.append(link.getJoinType().getExpression()).append(" ").append(toTableAlias).append(".")
					.append(link.getToColumnName());
		}
		return builder.toString();
	}

	@Override
	public String toString() {
		return "Join [fromTableName=" + fromTableName + ", fromTableAlias=" + fromTableAlias + ", toTableName="
				+ toTableName + ", toTableAlias=" + toTableAlias + ", joinType=" + joinType + ", links=" + links + "]";
	}

	public enum JoinType {
		/**
		 * Inner join.
		 */
		INNER("INNER JOIN"),

		/**
		 * Left outer join.
		 */
		LEFT("LEFT JOIN"),

		/**
		 * Right outer join.
		 */
		RIGHT("RIGHT JOIN"),

		/**
		 * Full outer join.
		 */
		FULL("FULL OUTER JOIN");

		private String expression;

		private JoinType(String expression) {
			this.expression = expression;
		}

		public String getExpression() {
			return expression;
		}

		public static JoinType getJoinType(String joinType) {
			return valueOf(joinType.toUpperCase());
		}
	}
}
