package com.its.pis.xnettcp.vds;

import com.its.pis.config.ControllerCommConfig;
import com.its.pis.entity.TbVdsCtlr;
import com.its.pis.global.AppRepository;
import com.its.pis.xnettcp.vds.process.VdsDataProcess;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

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

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

    private final ControllerCommConfig commConfig;
    private final VdsDataProcess vdsDataProcess;

    private VdsTcpClientBootstrapFactory bootstrapFactory;
    private ExecutorService executorService= Executors.newFixedThreadPool(1);
    private List<VdsTcpClient> clientTasks = Collections.synchronizedList(new ArrayList());

    @PostConstruct
    void init() {
        this.bootstrapFactory = new VdsTcpClientBootstrapFactory(1, this.commConfig.getConnectTimeout(), this.commConfig.isCommLogging(), vdsDataProcess);
    }

    public void run() {
        log.info("VdsTcpClientCommService.run: Start.");

        /**
         * 제어기접속
         */
        for (Map.Entry<String, TbVdsCtlr> e : AppRepository.getInstance().getCtlrMap().entrySet()) {
            TbVdsCtlr obj = e.getValue();
            if (StringUtils.equals("N", obj.getDEL_YN()) && StringUtils.equals("Y", obj.getVALD_YN())) {
                VdsTcpClient vdsClient = new VdsTcpClient(obj, this.commConfig, this.vdsDataProcess, this.bootstrapFactory);
                this.clientTasks.add(vdsClient);
            }
        }

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

        log.info("VdsTcpClientCommService.run: ..End.");
    }

    public void shutdown() {
        for (Map.Entry<String, TbVdsCtlr> e : AppRepository.getInstance().getCtlrMap().entrySet()) {
            TbVdsCtlr obj = e.getValue();
            if (obj.getChannel() != null) {
                obj.getChannel().close();
            }
        }
        this.bootstrapFactory.getEventLoopGroup().shutdownGracefully();
    }
}
