package com.yeejoin.amos.iec104.tcp;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PostConstruct;

import com.yeejoin.amos.connect.dao.entity.ConfigVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.yeejoin.amos.iec104.business.dao.repository.IServiceConfDao;
import com.yeejoin.amos.iec104.tcp.client.IEC104ClientManager;
import com.yeejoin.amos.iec104.tcp.client.Init;
import com.yeejoin.amos.iec104.tcp.client.invoke.ApduQueue;
import com.yeejoin.amos.iec104.tcp.client.invoke.GeneralDataQueue;
import com.yeejoin.amos.iec104.tcp.client.invoke.RecDataQueue;
import com.yeejoin.amos.iec104.tcp.server.IEC104Server;
import com.yeejoin.amos.iec104.tcp.server.session.SessionManager;
import com.yeejoin.amos.op.core.util.ApplicationConfig;

@Component("tcpServer")
@Scope("singleton")
public class TcpServer {

    @Autowired
	private ApplicationConfig applicationConfig;
	private static ConcurrentHashMap<Long, IEC104Server> servers = new ConcurrentHashMap<Long, IEC104Server>();
	
    @Autowired
    IEC104ClientManager iec104ClientManager;
    
    SessionManager sessionManager = SessionManager.getInstance();
    
    @Autowired
    private IServiceConfDao iServiceConfDao;
    
    @PostConstruct
	public void start() {
    	WebSocketQueue.getInstance().start();
    	Init.start();

    	List<ConfigVo> list = iServiceConfDao.findAllByServiceType("IEC_CLIENT");
    	for (ConfigVo vo : list) {
    		IEC104Server iec104Server = new IEC104Server();
    		iec104Server.setPort(Integer.parseInt(vo.getPort()));
    		iec104Server.setApplicationConfig(applicationConfig);
    		iec104Server.start();
    		servers.put(vo.getId(), iec104Server);
    	}

		iec104ClientManager.init();
		
		ApduQueue.getInstance().start();
		RecDataQueue.getInstance().start();
		GeneralDataQueue.getInstance().start();
	}
    
    public void createIecService(Long id, String port) {
    	IEC104Server iec104Server = new IEC104Server();
		iec104Server.setPort(Integer.parseInt(port));
		iec104Server.setApplicationConfig(applicationConfig);
		iec104Server.start();
		servers.put(id, iec104Server);
    }
    
    public void closeIecService(Long id) {
    	IEC104Server iec104Server = servers.get(id);
    	iec104Server.close();
    	servers.remove(id);
    }
}
