package com.its.op.xnettcp.client;

import com.its.op.config.VdsServerConfig;
import com.its.op.global.UnitSystManager;
import com.its.op.entity.its.unit.TbUnitSyst;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Slf4j
@Getter
@RequiredArgsConstructor
@Service
public class VdsCommClientService {

    private final VdsServerConfig vdsServerConfig;
    private NettyTcpClientVdsBootstrapFactory vdsBootstrapFactory;
    private NettyTcpClientVds vdsClient;
    private ExecutorService executorService= Executors.newFixedThreadPool(1);
    private List<NettyTcpClientVds> clientTasks = Collections.synchronizedList(new ArrayList());

    @PostConstruct
    void init() {
        this.vdsBootstrapFactory = new NettyTcpClientVdsBootstrapFactory(1, 5);
    }

    public void run() {
        log.info("VdsCommClientService.run: Start.");
        TbUnitSyst vdsServer = UnitSystManager.get(this.vdsServerConfig.getProcessId());
        if (vdsServer != null) {
            this.vdsServerConfig.setIpAddress(vdsServer.getSystIp1().trim());
            this.vdsServerConfig.setPort(Integer.parseInt(vdsServer.getPrgmPort().trim()));
        }
        log.info("{}", this.vdsServerConfig);

        /**
         * 클라이언트가 여러개 인 경우 여기서 추가해줌
         */
        for (int ii = 0; ii < 1; ii++) {
            this.vdsClient = new NettyTcpClientVds(
                    this.vdsServerConfig.getIpAddress(),
                    this.vdsServerConfig.getPort(),
                    this.vdsServerConfig.getReconnectTime(),
                    this.vdsBootstrapFactory
            );
            this.clientTasks.add(this.vdsClient);
        }

        try {
            List<Future<Object>> futures = this.executorService.invokeAll(this.clientTasks);
            log.info("VdsCommClientService.run: {}", futures);
        } catch(InterruptedException e) {
            log.error("run: Exception: InterruptedException");
        }

        log.info("===============================================================");
        log.info("=  VDS Communication Client Start.......................");
        log.info("=  ipAddress: {}", this.vdsServerConfig.getIpAddress());
        log.info("=       port: {}", this.vdsServerConfig.getPort());
        log.info("===============================================================");

        log.info("VdsCommClientService.run: ..End. {}", toString());
    }

}
