package com.cisdi.data.IDCardReader;

import com.alibaba.fastjson.JSON;
import com.cisdi.data.IDCardReader.gateway.impl.ZKIDROnlineClient;
import com.cisdi.data.IDCardReader.gateway.impl.ZKIDROnlineListener;
import com.cisdi.data.IDCardReader.gateway.vo.ZKIDROnlineConfigVo;
import com.cisdi.data.IDCardReader.gateway.vo.ZKIDROnlineResponseVo;
import com.cisdi.data.common.exception.BusinessException;
import com.cisdi.data.emserver.EmiaProSocketGateway;
import com.cisdi.data.sdk.consts.ServiceName;
import com.cisdi.data.sdk.enums.GatewayState;
import com.cisdi.data.sdk.gateway.base.SocketGatewayBase;
import com.cisdi.data.sdk.param.ListenSocketParam;
import com.cisdi.data.sdk.procotol.message.SocketReturnMessage;
import com.cisdi.data.sdk.service.RouteService;
import com.cisdi.data.sdk.vo.DeviceVo;
import com.cisdi.data.sdk.vo.ExeResultVo;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Set;

public class IDCardReaderGateway extends SocketGatewayBase {

    private static Logger logger = LoggerFactory.getLogger(IDCardReaderGateway.class);
    private ZKIDROnlineClient zkidrOnlineClient=null;
    private String deviceId;

    @Override
    public ExeResultVo sendReturnMessage(SocketReturnMessage returnMsg) {
        ExeResultVo resultVo = new ExeResultVo();
        resultVo.setMessage("该协议不允许下发数据");
        resultVo.setSuccess(false);
        logger.info("网关:{}->设备，消息:{},结果:{}",instanceVo.getRunId(), returnMsg, resultVo);
        return resultVo;
    }

    @Override
    public void start() {
        if (state == GatewayState.RUNNING) {
            return;
        }
        ListenSocketParam socketParam = JSON.parseObject(getInstanceVo().getParameter(), ListenSocketParam.class);

        String otherParameter = socketParam.getOtherParameter();
        ZKIDROnlineConfigVo zkidrOnlineConfigVo = null;
        // 处理分组
        if (StringUtils.isNotBlank(otherParameter)) {
            zkidrOnlineConfigVo = JSON.parseObject(otherParameter, ZKIDROnlineConfigVo.class);
        }
        if (zkidrOnlineConfigVo == null) {
            throw new BusinessException("网关Id:" + instanceVo.getRunId() + "为ZKIDROnline网关，请配置正确的ZKIDROnline配置");
        }

        RouteService routeService = (RouteService) serviceProvider.getByName(ServiceName.Route);
        List<DeviceVo> deviceVos = routeService.findByRunId(instanceVo.getRunId());

        if (deviceVos.size() > 1) {
            throw new BusinessException("网关Id:" + instanceVo.getRunId() + "为ZKIDROnline网关，只允许关联一个设备Id");
        }

        deviceId = deviceVos.size() > 0 ? deviceVos.get(0).getDeviceId() : null;

        if (StringUtils.isEmpty(deviceId)) {
            throw new BusinessException("runId=" + getInstanceVo().getRunId() + "未正确配置网关和设备关联");
        }
        logger.info("ZKIDROnline网关:{}读取启动配置参数:{}", instanceVo.getRunId(), getInstanceVo().getParameter());

        zkidrOnlineClient=new ZKIDROnlineClient(deviceId,serviceProvider,this,zkidrOnlineConfigVo);
        Thread thread=new Thread(zkidrOnlineClient);
        thread.start();
        state = GatewayState.RUNNING;
    }

    @Override
    public void shutdown() {
        if (state == GatewayState.CLOSED) {
            return;
        }
        if(zkidrOnlineClient.close())
        {
            state=GatewayState.CLOSED;
            logger.info("网关:" + instanceVo.getRunId() + "关闭成功", instanceVo.getRunId());
        }
    }

    @Override
    public Set<String> getActiveDeviceIds() {
        Set<String> set = Sets.newConcurrentHashSet();

        if (StringUtils.isNotEmpty(deviceId)) {
            set.add(deviceId);
        }

        return set;
    }
}
