package com.pwt.netty;

import com.pwt.Globals;
import com.pwt.netty.client.CodeScannerClient;
import com.pwt.netty.client.PlcClient;
import com.pwt.netty.client.RFIDClient;
import com.pwt.web.domain.PwtHolderBatteryStateCache;
import com.pwt.web.service.IPwtHolderBatteryStateCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
@Slf4j
public class PwtStopListener implements ApplicationListener<ContextClosedEvent> {

    @Autowired
    private CodeScannerClient codeScannerClient;

    @Autowired
    private RFIDClient rfidClient;

    @Autowired
    private Vehicle2Server vehicleServer;

    @Autowired
    private ChargerServer chargerServer;

    @Autowired
    private PlcClient plcClient;
    private IPwtHolderBatteryStateCacheService cacheService;

    @Autowired
    public void setCacheService(IPwtHolderBatteryStateCacheService cacheService) {
        this.cacheService = cacheService;
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        log.info("close app");
        // 停止时保存holder缓存
        Collection<PwtHolderBatteryStateCache> values = Globals.holderBatteryStateCacheMap.values();
        values.forEach((cache) -> {
            if(cache.getHolderId() <= Globals.ACTUAL_HOLDER_COUNT) {
                try{
                    cacheService.updateBatteryStateCacheRecord(cache);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //close();
    }

    private void close() {
        try {
            plcClient.stop();
            codeScannerClient.stop();
            rfidClient.stop();
            vehicleServer.stop();
            chargerServer.stop();
            log.info("关闭所有服务");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
