package jp.agentec.sinaburocast.service;

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

import jp.agentec.sinaburocast.common.util.SinaburoUtil;
import jp.agentec.sinaburocast.entity.OperationHistory;
import jp.agentec.sinaburocast.form.admin.setting.OperationHistoryForm;

import org.apache.velocity.tools.generic.DateTool;
import org.seasar.extension.jdbc.AutoSelect;
import org.seasar.extension.jdbc.where.SimpleWhere;
import org.seasar.framework.container.annotation.tiger.Component;
import org.seasar.framework.container.annotation.tiger.InstanceType;
import org.seasar.framework.util.StringUtil;
@Component(instance=InstanceType.SINGLETON)
public class OperationHistoryService extends AbstractService<OperationHistory> {

	
	public static final String ID_SEQ_NAME = "operation_history_id_seq";

	/**
	 * IDを発行して、登録する。
	 */
	public int insertOperationHistory(OperationHistory operationHistory, String insId) {
		operationHistory.operationHistoryId =
				getSeqNextVal(Long.class, ID_SEQ_NAME);
		return super.insert(operationHistory, insId);
	}
	
    public OperationHistory findById(Long operationHistoryId) {
        return select().id(operationHistoryId).getSingleResult();
    }

    public List<OperationHistory> findAllOrderById() {
        return select().orderBy("operationHistoryId asc").getResultList();
    }
    
    /**
     * 操作履歴画面での検索
     * @return
     */
    public List<OperationHistory> searchOperationHistory(OperationHistoryForm operationHistoryForm){
    	
    	long cnt = getOperationHistoryAutoSelect(operationHistoryForm).getCount();
    	operationHistoryForm.setPaging(null, operationHistoryForm.pageNo, cnt);
    	
    	return getOperationHistoryAutoSelect(operationHistoryForm).orderBy("insertDate desc")
    			.offset(operationHistoryForm.getOffSet(null))
    			.limit(operationHistoryForm.getLimit(null))
    			.getResultList();  
    	
    }
    
    /**
     * 操作履歴画面での検索
     * @return
     */
    private AutoSelect<OperationHistory> getOperationHistoryAutoSelect(OperationHistoryForm operationHistoryForm){
    	
    	AutoSelect<OperationHistory> autoSelect = select().innerJoin("operationType");
    	SimpleWhere simpleWhere = new SimpleWhere();
    	if(!StringUtil.equals(operationHistoryForm.selectAdmin, "0")){//全部ではない場合
    		simpleWhere = simpleWhere.eq("adminUserId", operationHistoryForm.selectAdmin);
    	}
    	
    	if(StringUtil.isNotBlank(operationHistoryForm.searchFrom)){//fromを入力した場合
    		simpleWhere = simpleWhere.ge("insertDate", SinaburoUtil.convertStringToTimestamp(operationHistoryForm.searchFrom,"yyyy-MM-dd"));
    	}
    	
    	if(StringUtil.isNotBlank(operationHistoryForm.searchTo)){//toを入力した場合。
    			
    			
    		simpleWhere = simpleWhere.lt("insertDate",SinaburoUtil.convertStringToTimestamp(SinaburoUtil.getNextDay(operationHistoryForm.searchTo),"yyyy-MM-dd"));
    	}
    	
    	return autoSelect.where(simpleWhere).innerJoin("adminUser").innerJoin("screen");
    	
    }
    
    
}