package com.eactive.eai.batch.rule.dirInfo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;


import com.eactive.eai.common.util.Logger;

public class BatchJobPriorityManager  implements Serializable
{

    private static final long serialVersionUID = 1L;
    //    파일로거
    private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
    private static BatchJobPriorityManager instance = new BatchJobPriorityManager();

    private HashMap<String, ArrayList<BatchJobPriorityVO>> hmPrioritys;
    private HashMap<String, Long>                          hmDelays;

    private BatchJobPriorityManager() {       
        hmPrioritys = new HashMap<String, ArrayList<BatchJobPriorityVO>>();
        hmDelays    = new HashMap<String, Long>();
    }

    public static BatchJobPriorityManager getInstance() {
        return instance;
    }
    
    
    public synchronized void addJobPriorityData(String key, ArrayList<BatchJobPriorityVO> list)
    {
        Object obj = hmPrioritys.get(key);
        if (obj != null) {
            logger.warn("[ BatchJobPriorityManager ] addJobPriorityData >> UUID["+key+"] 에 이미 데이터가 있습니다." + obj);
            hmPrioritys.remove(key);
        }
        hmPrioritys.put(key, list);
    }

    public synchronized  ArrayList<BatchJobPriorityVO> getPriorityData(String key)
    {       
        return  hmPrioritys.get(key);
    }

    public synchronized  void setPriorityData(String key, ArrayList<BatchJobPriorityVO> hm)
    {
        hmPrioritys.remove(key);
        hmPrioritys.put(key, hm);
    }

    public synchronized  void delPriorityData(String key)
    {
        this.hmPrioritys.remove(key);
    }

    public synchronized int getPriorityDataCount() {
        return hmPrioritys.size();
    }
    

    public synchronized boolean isExecutePrePriority (String key, String bizCode) throws Exception{
        
        try {
            ArrayList<BatchJobPriorityVO> list = getPriorityData(key);
            
            if (list != null && list.size() > 0){
                for (int i=0; i < list.size(); i++){
                    BatchJobPriorityVO bjpvo = (BatchJobPriorityVO)list.get(i);
                    if (bizCode.equals(bjpvo.getBizCode())){
                        if (i == 0){//첫번째 우선순위 목록에 있으면 무조건 선순위 작업 실행 여부는 true. 
                            return true;
                        }else {
                            BatchJobPriorityVO pjpvo = (BatchJobPriorityVO)list.get(i-1);
                            if (pjpvo !=null){
                                return pjpvo.isExecuted();
                            }
                        }
                    }
                }
            }else {
                return false;
            }
        }catch (Exception e){
            logger.error("[ BatchJobPriorityManager ] 배치우선작업 처리 여부 확인 시 에러가 발생했습니다. - "+e.getMessage());
            throw new Exception ("[ BatchJobPriorityManager ] 배치우선작업 처리 여부 확인 시 에러가 발생했습니다. - "+e.getMessage());
        }
        return false;
    }
    
    public synchronized void updateExecuteJobList(String key, String bizCode, String uuid, String fileName)throws Exception{
      
        try{
            ArrayList<BatchJobPriorityVO> list = getPriorityData(key);
            
            if (list != null && list.size() > 0){
                for (int i=0; i < list.size(); i++){
                    BatchJobPriorityVO bjpvo = (BatchJobPriorityVO)list.get(i);
                    if (bizCode.equals(bjpvo.getBizCode())){
                    	
                        bjpvo.setUUID(uuid);
                        bjpvo.setFileName(fileName);
                        bjpvo.setExecutedFlag(true);
                    }
                }
            }        
        }catch (Exception e){
            logger.error("[ BatchJobPriorityManager] 배치우선작업 처리 결과 변경시  에러가 발생했습니다. - "+e.getMessage());
            throw new Exception ("[ BatchJobPriorityManager] 배치우선작업 처리처리 결과 변경시  에러가 발생했습니다. - "+e.getMessage());
        }
         
    }
    
    public synchronized BatchJobPriorityVO getPriorityDatabyBizCode(String key, String bizCode)throws Exception{

        try {
            ArrayList<BatchJobPriorityVO> list = getPriorityData(key);
            BatchJobPriorityVO bjpvo = null;
            if (list != null && list.size() > 0){
                for (int i=0; i < list.size(); i++){
                    bjpvo = (BatchJobPriorityVO)list.get(i);
                    if (bizCode.equals(bjpvo.getBizCode())){
                        break;
                    }
                }
            }
            return bjpvo;
        }catch (Exception e){
            logger.error("[ BatchJobPriorityManager ] 배치우선작업 처리 여부 확인 시 에러가 발생했습니다. - "+e.getMessage());
            throw new Exception ("[ BatchJobPriorityManager ] 배치우선작업 처리 여부 확인 시 에러가 발생했습니다. - "+e.getMessage());
        }
    }
    
    public synchronized HashMap<String, ArrayList<BatchJobPriorityVO>> getPriorityDatas() {
        return hmPrioritys;
    }
    
    public String[] getPriorityKeys() {
        Iterator<String> it = this.hmPrioritys.keySet().iterator();
        String[] key = new String[this.hmPrioritys.size()];
        for(int i=0;it.hasNext();i++) {
            key[i] = (String)it.next();
        }

        Arrays.sort(key);
        return key;
    }
    
    public synchronized  void setDelaySec(String uuid, long sec){
        hmDelays.put(uuid, new Long(sec));
    }
    
    public synchronized boolean hasDelaySec(String uuid){
        return hmDelays.containsKey(uuid);
    }
    
    public synchronized long getDelaySec(String uuid){
        long delay = 0; 
        try {
            delay = (hmDelays.get(uuid)).longValue();
        }catch (Exception e){
            logger.error("[ BatchJobPriorityManager ] Delay seconds 를 가져오는데 실패했습니다.- " + e.getMessage());
            delay = -1;
            //값변환시 에러이면 -1을 반환..
        }
        return delay;
    }
    
    public synchronized void removeDelaySec(String uuid){
        
        try{
            hmDelays.remove(uuid);
        }catch (Exception e){
            logger.error("[ BatchJobPriorityManager ] removeDelaySec - Delay seconds 를 초기화 하는데  실패했습니다.- "+e.getMessage());
        }
    }
}
