package com.eactive.eai.rms.client.agent;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.rms.client.SocketClient;
import com.eactive.eai.rms.onl.vo.AdaptersStatusVO;

public class AdaptersStatusAgent extends AbstractScheduledAgent {

	private SocketClient socketClient;

	public void run() {
		AdaptersStatusVO adaptersStatusVO = (AdaptersStatusVO) applicationContext.getBean("adaptersStatusVO");
		setAdapters(adaptersStatusVO);
		socketClient.send(adaptersStatusVO);
	}

	public void setSocketClient(SocketClient socketClient) {
		this.socketClient = socketClient;
	}

	public AdaptersStatusVO getAdapterStatusInfo() {
		AdaptersStatusVO adaptersStatusVO = new AdaptersStatusVO();
		setAdapters(adaptersStatusVO);
		return adaptersStatusVO;
	}

	public void setAdapters(AdaptersStatusVO adapterStatus) {
		AdapterManager manager = AdapterManager.getInstance();
		HashMap<String, AdapterGroupVO> voMap = manager.getAllAdapterGroupVO();

		Iterator<String> it = voMap.keySet().iterator();

		String[] groupNames = new String[voMap.size()];

		for (int i = 0; it.hasNext(); i++) {
			groupNames[i] = it.next();
		}

		Arrays.sort(groupNames);

		for (int i = 0; i < groupNames.length; i++) {
			AdapterGroupVO gvo = manager.getAdapterGroupVO(groupNames[i]);
			adapterStatus.setAdapter(groupNames[i], gvo.isAlive());
		}
	}
}
