package com.eactive.eai.agent.adapter.socket;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.eactive.eai.adapter.socket.service.SocketService;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommandException;
import com.eactive.eai.batch.doc.BatchDoc;
import com.eactive.eai.batch.running.BatchRunningJobManager;
import com.eactive.eai.common.util.Logger;

public class SocketSessionCommand  extends Command
{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

    public SocketSessionCommand(String name) {
        super(name);
    }

    public Object execute() throws CommandException
    {
        logger.info(this.name + " Agent 가 호출되었습니다.");

        try {
        	List<Map<String, String>> alist = getAllRunningSessionVO();

			logger.info(this.name + " Agent 가 성공적으로 완료되었습니다.");
            return alist;

        } catch (Exception ex) {
            String msg = makeException("BECEAICAG002", ex);
            logger.error(msg, ex);
            throw new CommandException(msg);
        }
    }


    
    private List<Map<String, String>> getAllRunningSessionVO() throws Exception {
    	List<Map<String, String>> retList = new ArrayList<Map<String, String>>();

		HashMap<String, BatchDoc> allDocs = BatchRunningJobManager.getInstance().getAllRunningDocuments();
		Object[] uuids = allDocs.keySet().toArray();
        
        for (int i=0; i<allDocs.size(); i++) {
            BatchDoc      batchDoc = (BatchDoc)      BatchRunningJobManager.getInstance().getRunningDocument((String)uuids[i]);
            SocketService service  = (SocketService) BatchRunningJobManager.getInstance().getRunningSocketService((String)uuids[i]);
            
            //socket 이 null 이거나 remote address 가 null 이어서 remote에 연결되지 않은 소켓은 목록에 추가 안함
            if (service == null ) {
                continue;
            }
            
            Date date = new Date(service.getFirstActivity());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String timestamp = sdf.format(date);

            Map<String, String> map = new HashMap<String, String>();
            map.put( "serverName"      , batchDoc.getBatchMsg().getBody().getWLIServerName());
            map.put( "processName"     , batchDoc.getBatchMsg().getHeader().getProcessName());
            map.put( "organName"       , batchDoc.getBatchMsg().getHeader().getInstitutionName());
            map.put( "processType"     , batchDoc.getBatchMsg().getHeader().getProcessType());
            map.put( "uuid"            , batchDoc.getBatchMsg().getHeader().getUUID());
            map.put( "adapterGroupName", service.getContext()==null? "" : service.getContext().getAdapterGroupName());
            map.put( "adapterName"     , service.getContext()==null? "" : service.getContext().getAdapterName());
            map.put( "localIpPort"     , service.getCurrentSocket() == null || service.getCurrentSocket().getLocalAddress() == null?
            		                     "" :
            		                     service.getCurrentSocket().getLocalAddress().getHostAddress() + ":" + service.getCurrentSocket().getLocalPort());
            map.put( "remoteIpPort"    , service.getCurrentSocket() == null || service.getCurrentSocket().getInetAddress() == null ?
            		                     "" :
            		                     service.getCurrentSocket().getInetAddress().getHostAddress() + ":" + service.getCurrentSocket().getPort());
            map.put( "startTimeStamp"  , timestamp);
            map.put( "status"          , "연결됨");
            retList.add(map);
        }
        return retList;
    }
}