package kr.co.kihyun.beans.entity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import kr.co.kihyun.lang.MString;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class ExecutionCode {
	private static final Logger LOG = LoggerFactory.getLogger(ExecutionCode.class);

	private String deptName;

	private Integer number;

	private Date date;

	public ExecutionCode() {
	}

	public ExecutionCode(String deptName, Integer number, Date date) {
		this.setDeptName(deptName);
		this.setNumber(number);
		this.setDate(date);
	}

	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}

	public String getDeptName() {
		return deptName;
	}

	public final Integer getNumber() {
		return number;
	}

	public final void setNumber(Integer number) {
		this.number = number;
	}

	public final Date getDate() {
		return date;
	}

	public final void setDate(Date date) {
		this.date = date;
	}

	public static ExecutionCode valueOf(String codeString) throws IllegalArgumentException {
		try {
			String deptName = codeString.split("_")[0];
			int number = Integer.parseInt(codeString.split("[_\\(]")[1]);
			String dateStr = codeString.split("[\\(\\)]")[1];
			Date date = null;
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				date = sdf.parse(dateStr);
			} catch (ParseException pe) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
				date = sdf.parse(dateStr);
			}
			return new ExecutionCode(deptName, number, date);
		} catch (Exception e) {
			throw new IllegalArgumentException("\""+codeString+"\" is not a valid execution code.");
		}
	}

	@Override
	public String toString() {
		String dateStr = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
		try {
			if (this.getDate() != null)
				dateStr = sdf.format(this.getDate());
		} catch (Exception e) {
			LOG.error("Unable to format date for {}", this.getDate());
		}
		if(MString.isNull(this.getDeptName()) && this.getNumber() == null && this.getDate() == null)
			return "";
		return MString.checkNull(this.getDeptName())+"_"+MString.checkNull(String.valueOf(this.getNumber()))+"("+dateStr+")";
	}
}
