package kr.co.kihyun.beans.entity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.Discriminator;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.Inheritance;
import javax.jdo.annotations.InheritanceStrategy;
import javax.jdo.annotations.PersistenceCapable;

import kr.co.kihyun.beans.entity.util.QueryImpl;
import kr.co.kihyun.moumi.MoumiConfig;

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

@PersistenceCapable(identityType = IdentityType.APPLICATION)
@Inheritance(strategy = InheritanceStrategy.SUPERCLASS_TABLE)
public class LimitByDeadlineStrategy extends AcceptanceLimitStrategy {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5531410697614923017L;
	private static final Logger LOG = LoggerFactory.getLogger(LimitByDeadlineStrategy.class);

	private static final String filter =
		"isDeleted == 'N' && type == TYPE_REPORT && " +
		"(process == PROCESS_COMP || process == PROCESS_END || process == PROCESS_NOT) && " +
		"submitDate <= tot_doc.endDate && totDoc == tot_doc";

	public LimitByDeadlineStrategy() {
	}

	public LimitByDeadlineStrategy(Long limitCount) {
		super(limitCount);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TotReport> getCompReports(PersistenceManager pm, Map<String, Object> filterMap) {
		QueryImpl q = new QueryImpl(pm, TotReport.class);
		q.setFilter(filter);
		q.setSearchFilter(filterMap);
		q.declareParameters("kr.co.kihyun.beans.entity.TotDoc tot_doc");
		q.setOrdering("mDept");
		return (List<TotReport>) q.execute(this.getTotDoc());

	}

	@Override
	public TotDocProcess getProcess(PersistenceManager pm) {
		LOG.debug("startDate: {}, endDate: {}, sysdate: {}, prss: {}",
				new Object[] {this.getTotDoc().getStartDate(), this.getTotDoc().getEndDate(), new Date(), this.getProcess()});
		if (this.getProcess() == TotDocProcess.PRSS && this.getTotDoc().getEndDate().before(new Date()))
			return TotDocProcess.END;
		if (this.getTotDoc().getStartDate() == null ||
				(this.getTotDoc().getStartDate().after(new Date()) && this.getProcess() == TotDocProcess.PRSS))
			return TotDocProcess.REG;
		return this.getProcess();
	}

	@Override
	public String getDescription(PersistenceManager pm) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
		return sdf.format(this.getTotDoc().getEndDate())+MoumiConfig.getMessageBundle().getString("moumi.message.hour")+
		" "+MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.end");
	}

}
