package com.eactive.eai.rms.bat.manage.rule.cron;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eactive.eai.rms.bat.common.base.BatBaseService;
import com.eactive.eai.rms.common.util.StringUtils;

@Service("batCronService")
public class BatCronService extends BatBaseService {

	@Autowired
	@Qualifier("batCronDao")
	private BatCronDao dao;

	public HashMap<String, Object> selectList(int startNum,int endNum, String searchSchedId) throws Exception {
		
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		//검색 조건 
		paramMap.put("searchSchedId", searchSchedId);
 
		
		// 전체 목록수 얻기
		int totalCount = dao.selectListCount(paramMap);

		paramMap.put("startNum" , startNum);// 시작 record
		paramMap.put("endNum"   , endNum);// 끝 record

		List<Map<String, Object>> list = dao.selectList(paramMap);
		for(Map<String, Object> m : list){
			String Desc = makeCronDesc(m);
			m.put("CRONDESC", Desc);
		}
		HashMap<String, Object> map = new HashMap<String, Object>();

		map.put("totalCount", totalCount);

		map.put("list", list);

		return map;
	}	

	public HashMap<String, Object> selectDetail(String schedId) throws Exception {

		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("schedId", schedId);

		return dao.selectDetail(paramMap);

	}	

	public void update(HashMap<String, Object> paramMap) throws Exception {
		dao.update(paramMap);
	}	

	public void insert(HashMap<String, Object> paramMap) throws Exception {
		dao.insert(paramMap);
	}
	
	public void delete(HashMap<String, Object> paramMap) throws Exception {
		dao.delete(paramMap);
	}

	public String makeCronDesc(Map m) throws Exception{
			//배치는 분, 초단위이기 때문에 월 일 시 조립X
			String Desc = "매시 ";
			String cronExp = (String)m.get("CRONEXP");
			
			String[] cron = StringUtils.split(cronExp," ");
			String[] gubun = {"초","분"};
			for(int i =2 ; i >= 0; i--){
				if(!"*".equals(cron[i]) && !"?".equals(cron[i])){
					if(cron[i].indexOf("/") > -1){
						String[] fromTo = StringUtils.split(cron[i], "[/]"); 
						if("*".equals(fromTo[0])){
							Desc = Desc + cron[0] +gubun[0]+" 부터 " + fromTo[1] +gubun[1]+" 간격으로 ";
							break;
						}else{
							Desc = Desc + fromTo[0] +gubun[i]+" 부터 " + fromTo[1] +gubun[i]+" 간격으로 ";
						}
					}else{
						Desc = Desc + cron[1] +gubun[1] +" ";
					}
				}
			}

		return Desc;
	}
}
	