package com.willalp.control.netty.handler;

import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.StringUtils;
import com.willalp.control.netty.model.ChannelMsgModel;
import com.willalp.control.netty.model.ControlDataModel;
import com.willalp.control.netty.model.DeviceChannelMap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

/**
 * 任务下达socket发送消息
 *
 * @author hs
 */
public class RwxdSocket {
    private static final Logger logger = LoggerFactory.getLogger(RwxdSocket.class);

    /**
     * 推送指令到基站
     */
    public static boolean sendDeviceCommand(String command, String lockIp) {
        synchronized (ControlDataModel.WAIT_MAP) {
            //当前IP不存在时新增到map中
            ControlDataModel.WAIT_MAP.computeIfAbsent(lockIp, k -> new Date());
            long time = System.currentTimeMillis() - ControlDataModel.WAIT_MAP.get(lockIp).getTime();
            try {
                if (1000 > time) {
                    //保证每个IP发送信息时都能间隔1s
                    Thread.sleep(1000 - time);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (StringUtils.isBlank(command)) {
                throw new BaseException("指令不能为空！");
            }
            if (StringUtils.isBlank(lockIp)) {
                throw new BaseException("基站IP不能为空！");
            }
            //获取所有通道
            Map<String, ChannelMsgModel> allChannelMap = DeviceChannelMap.getAll();
            if (0 == allChannelMap.size()) {
                throw new BaseException("control.openOrClose.device.not.network", new Object[]{allChannelMap});
            }
            //循环通道
            for (String remoteAddress : allChannelMap.keySet()) {
                if (lockIp.equals(remoteAddress)) {
                    byte[] bytes = command.getBytes(StandardCharsets.UTF_8);
                    ByteBuf resp = Unpooled.copiedBuffer(bytes);
                    Channel channel = allChannelMap.get(remoteAddress).getChannel();
                    channel.writeAndFlush(resp);
                    logger.info("成功向设备(" + remoteAddress + ")下达指令：" + command);
                    ControlDataModel.WAIT_MAP.put(lockIp, new Date());
                    return true;
                }
            }
            throw new BaseException("IP地址为：" + lockIp + "的基站未建立连接");
        }
    }
}
