package com.zd.netty.init;

import com.zd.common.core.constant.HttpStatus;
import com.zd.common.core.domain.R;
import com.zd.netty.service.IFridService;
import com.zd.system.api.laboratory.RemoteLaboratoryService;
import com.zd.system.api.laboratory.domain.RemoteLabHardware;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 监听Spring容器启动完成，完成后启动Netty服务器
 *
 * @author dgs
 **/
@Component
@Slf4j
public class NettyStartListener implements ApplicationRunner {
    @Resource
    private IFridService fridService;
    @Resource
    private RemoteLaboratoryService laboratoryService;
    @Resource
    private SocketServer socketServer;


    @Override
    public void run(ApplicationArguments args) {
        R<List<RemoteLabHardware>> listStart = laboratoryService.listStart();
        synchronized (this){
            while (listStart.getCode() != HttpStatus.SUCCESS) {
                try {
                    log.error("com.zd.system.api.laboratory.RemoteLaboratoryService:远程接口调用异常");
                    //防止laboratory模块未启动完成，故每30秒执行一次程序，直到接口可以正常访问
                    this.wait(30 * 1000L);
                    NettyStartListener.this.run(args);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            List<RemoteLabHardware> unitVos = listStart.getData();
            if (!unitVos.isEmpty()) {
                try {
                    unitVos.stream()
                            .filter(u -> StringUtils.hasLength(u.getIpAddress()))
                            .forEach(u -> fridService.start(u));
                } catch (Exception e) {
                    e.fillInStackTrace();
                }
            }
        }
    }
}
