package com.zd.netty.service.impl;

import com.zd.common.core.utils.SpringUtils;
import com.zd.netty.enums.ManufacturerTypeEnum;
import com.zd.netty.service.IFridService;
import com.zd.netty.service.IService;
import com.zd.system.api.laboratory.domain.RemoteLabHardware;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.zd.common.core.constant.Constants.MAP_INIT_SIZE;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class FridServiceImpl implements IFridService {

    private final ThreadPoolTaskExecutor taskExecutor = SpringUtils.getBean("taskExecutor");

    private final Map<String, Thread> threadMap = new HashMap<>(MAP_INIT_SIZE);

    private IService rfidService(Integer type) {
        return SpringUtils.getBean(ManufacturerTypeEnum.matchByValue(type).getService());
    }

    @Override
    public void start(RemoteLabHardware hardware) {
        synchronized (this){
            taskExecutor.execute(() -> {
                rfidService(hardware.getManufacturerType()).start(hardware);
                log.info("===================thread name:{}===============", Thread.currentThread().getName());
                threadMap.computeIfAbsent(hardware.getIpAddress(), f -> Thread.currentThread());
                log.info("==============>线程数量：{}",threadMap.size());
            });
        }
    }

    @Override
    public void stop(RemoteLabHardware hardware) {
        rfidService(hardware.getManufacturerType()).disconnect(hardware);
        Thread thread = threadMap.get(hardware.getIpAddress());
        if (thread != null && thread.isAlive()) {
            thread.interrupt();
            threadMap.remove(hardware.getIpAddress());
        }
    }

    @Override
    public boolean alarm(RemoteLabHardware hardware) {
       return rfidService(hardware.getManufacturerType()).alarm(hardware);
    }
}
