package com.inspect.patrol.linkage.frame;

//import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.buffer.ByteBuf;
//import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.buffer.Unpooled;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import com.inspect.base.core.utils.SpringUtils;
import com.inspect.base.redis.service.RedisService;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.inspect.patrol.linkage.constain.LinkageContain.REDIS_DEVICE_INFO_FRAME;
import static com.inspect.patrol.linkage.constain.LinkageContain.REDIS_DEVICE_INFO_FRAME_NUM;

public class DeviceInfoFrame {
   private DeviceInfoByte deviceInfoByte;
   private DeviceInfoEntity deviceInfoEntity;
   RedisService redisService;

   public String parse(byte[] bytes) throws UnsupportedEncodingException {
      this.deviceInfoByte = new DeviceInfoByte(bytes);
      this.deviceInfoEntity = this.deviceInfoByte.toDeviceInfoEntity();
      this.redisService = SpringUtils.getBean(RedisService.class);
      this.redisService.setCacheMapValue(REDIS_DEVICE_INFO_FRAME, String.valueOf(this.deviceInfoEntity.getFrameNo()), this.deviceInfoEntity.getContent());
      if(this.deviceInfoEntity.getSubBit() == 0) {
         this.redisService.redisTemplate.opsForValue().set(REDIS_DEVICE_INFO_FRAME_NUM, this.deviceInfoEntity.getFrameNo() + 1);
      }

      Object o = this.redisService.redisTemplate.opsForValue().get(REDIS_DEVICE_INFO_FRAME_NUM);
      if(o != null && this.redisService.getCacheMap(REDIS_DEVICE_INFO_FRAME).size() == ((Integer)o).intValue()) {
         Map<String, Object> cacheMap = this.redisService.redisTemplate.opsForHash().entries(REDIS_DEVICE_INFO_FRAME);
         this.redisService.redisTemplate.delete(REDIS_DEVICE_INFO_FRAME);
         this.redisService.redisTemplate.delete(REDIS_DEVICE_INFO_FRAME_NUM);
         List<byte[]> list = new ArrayList();

         for(int i = 0; i < cacheMap.size(); ++i) {
            String content = (String)cacheMap.get(String.valueOf(i));
            list.add(Base64.getDecoder().decode(content));
         }

         ByteBuf byteBuf = Unpooled.buffer();
         list.forEach((item) -> {
            byteBuf.writeBytes(item);
         });
         byte[] contentBytes = new byte[byteBuf.readableBytes()];
         byteBuf.getBytes(0, contentBytes);
         return new String(contentBytes, "GB2312");
      } else {
         return null;
      }
   }

   public List<byte[]> combine(String content, short stationNo) throws UnsupportedEncodingException {
      this.deviceInfoEntity = new DeviceInfoEntity(content, stationNo);
      List<DeviceInfoByte> deviceInfoBytes = this.deviceInfoEntity.toDeviceInfoBytes();
      return (List)deviceInfoBytes.stream().map((item) -> {
         return item.toBytes();
      }).collect(Collectors.toList());
   }
}
