package kr.co.kihyun.beans.entity;

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

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
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;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
@Inheritance(strategy = InheritanceStrategy.SUPERCLASS_TABLE)
public class LimitByWriteDateStrategy extends AcceptanceLimitStrategy {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3702862598458450856L;
	private static final String filter =
		"isDeleted == 'N' && type == TYPE_REPORT && " +
		"(process == PROCESS_COMP || process == PROCESS_END || process == PROCESS_NOT) && " +
		"totDoc == tot_doc";

	public LimitByWriteDateStrategy() {
	}

	public LimitByWriteDateStrategy(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("writeDate");
		q.setRange(0, this.getLimitCount());
		return (List<TotReport>) q.execute(this.getTotDoc());
	}

	@Override
	public TotDocProcess getProcess(PersistenceManager pm) {
		Query q = pm.newQuery(TotReport.class);
		q.setResult("count(this)");
		q.setFilter(filter);
		q.declareParameters("kr.co.kihyun.beans.entity.TotDoc tot_doc");
		if ((Long) q.execute(this.getTotDoc()) >= this.getLimitCount())
			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) {
		Query q = pm.newQuery(TotReport.class);
		q.setResult("count(this)");
		q.setFilter(filter);
		q.declareParameters("kr.co.kihyun.beans.entity.TotDoc tot_doc");
		return MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.endByWriteCount")+" - "+
		(Long) q.execute(this.getTotDoc())+"/"+this.getLimitCount()+
		MoumiConfig.getMessageBundle().getString("moumi.message.people");
	}
}
