package com.eactive.eai.agent.command;

import java.io.Serializable;
import java.util.HashMap;

/** 
* 1. 기능 : Agent에 의해 실행될 Command 를 정의하기 위한 base class
* 2. 처리 개요 : Agent에 의해 실행될 Command 를 정의하기 위한 base class
* 3. 주의사항 
*
* @author  
* @version  v 1.0.0
* @see  관련 기능을 참조
* @since   
*  
*/
public abstract class Command implements Serializable {
	private static final long serialVersionUID = 1L;
	/** Command object name */
	protected String name;
	/** Command Arguments */
	protected Object args;
	
	private static HashMap<String,String> errorCode ;
	
	static {
        errorCode = new HashMap<>();
        errorCode.put("RECEAIMCM001", "Command name[{1}] invalid parameter type - {2}");
        errorCode.put("RECEAIMCM002", "Command name[{1}] execute method error - {2}");		
	}
	
	public Command() {
		this.name = this.getClass().getName();	
	}
	
	public Command(String name) {
		this.name = name;	
	}

	public void setArgs(Object args) {
		this.args = args;	
	}
	
	
	public abstract Object execute() throws CommandException;	
    
    protected String makeException(String rspErrorCode, Throwable cause){
        String[] msgArgs = new String[2];
        msgArgs[0] = name;
        if(cause == null){
            msgArgs[1] = args.toString();
        }
        else{
            msgArgs[1] = cause.getMessage();
        }
        String msg = makeMessage(errorCode.get(rspErrorCode),msgArgs) ;
        
        return msg;
    }

    private static String makeMessage(String msg, String[] args) {
        String keyword = null, head = null, tail = null;
        int idx = -1;
        for(int i=0;i<args.length;i++) {
            keyword = "{"+(i+1)+"}";
            idx = msg.indexOf(keyword);
            if(idx == -1) {
                continue;
            }
            head = msg.substring(0,idx);
            tail = msg.substring(idx+keyword.length());
            msg = head+args[i]+tail;
        }
        return msg;
    }

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
