package com.xydl.cac.iec104;

import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.model.StaticVariable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Service
@Slf4j
public class Iec104ServerService {


    @PostConstruct
    private void init() {
        try {
//            this.startServer(2404);
        } catch (Exception ignore) {
        }
    }

    public void startServer(int port) throws BusinessException {
        try {
            Iec104Server server = new Iec104Server();
            server.start(port);
            StaticVariable.iec104Server = server;
        } catch (Exception e) {
            log.error("启动IEC104服务端异常.", e);
            throw new BusinessException(e.getMessage());
        }
    }

    public void stopServer() {
        this.doStopServer();
    }

    private void doStopServer() {
        if (StaticVariable.iec104Server != null) {
            StaticVariable.iec104Server.stop();
            StaticVariable.iec104Server = null;
        }
    }

    @PreDestroy
    private void stop() {
        StaticVariable.shutdown = 1;
        this.doStopServer();
    }

}
