package com.docus.server.service.impl;

import com.docus.core.util.DateUtil;
import com.docus.core.util.json.JSON;
import com.docus.server.common.CommMsg;
import com.docus.server.common.netty.server.TerminalToChannelCacheMap;
import com.docus.server.convert.CommMsgConvert;
import com.docus.server.dto.scheduling.management.schterminator.CommMsgDTO;
import com.docus.server.service.ICommMsgService;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
public class CommMsgServiceImpl implements ICommMsgService {

    @Resource
    private TerminalToChannelCacheMap channelRepository;

    @Override
    public void clientCommand(CommMsgDTO commMsgDTO) {
        Channel channel = channelRepository.get(commMsgDTO.getTerminatorIp());

        CommMsg commMsg = CommMsgConvert.INSTANCE.convertDO(commMsgDTO);
        commMsg.setMessageTime(DateUtil.formatDateTime(new Date()));

        if (channel != null) {
            channel.writeAndFlush(Unpooled.copiedBuffer(JSON.toJSON(commMsg), CharsetUtil.UTF_8));
        }
    }

    @Override
    public void clientsCommand(CommMsgDTO commMsgDTO) {

        Map<String, Channel> channelMap = channelRepository.getIpToChannelCacheMap();
        Set<String> keySet = channelMap.keySet();

        for (String clientIp : keySet) {
            Channel channel = channelMap.get(clientIp);

            CommMsg commMsg = CommMsgConvert.INSTANCE.convertDO(commMsgDTO);
            commMsg.setMessageTime(DateUtil.formatDateTime(new Date()));

            if (channel != null) {
                channel.writeAndFlush(Unpooled.copiedBuffer(JSON.toJSON(commMsg), CharsetUtil.UTF_8));
            }

        }
    }
}
