package server;

import client.GpsDto;
import client.SimplePoint;
import client.TcpClient;
import client.TcpClientHandler;
import com.alibaba.fastjson.JSON;
import com.fazecast.jSerialComm.SerialPort;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yuli
 * @ClassName TcpServerHandler
 **/
public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {

    private static Logger logger = LoggerFactory.getLogger(TcpServerHandler.class);
//    public static final MediaType JSON  = MediaType.get("application/json; charset=utf-8");

//    public static  String serverUrl;

    //全局变量
    private static  Map<String, ChannelHandlerContext> gpsServerContextHashMap = new HashMap<>();
    //获取全局变量信息
    public ChannelHandlerContext getContext(String key){
        return gpsServerContextHashMap.get(key);
    }
    //更新全局变量信息
    public void addContext(String key,ChannelHandlerContext ctx){
        gpsServerContextHashMap.put(key,ctx);
    }
    //清空全局变量信息
    public void deleteContext(String key){
        gpsServerContextHashMap.remove(key);
    }

    /**
        * 打印接收到的内容，并回传
         //        * @paractx = {DefaultChannelHandlerContext@2874} "ChannelHandlerContext(TcpServerHandler#0, [id: 0xe24a52fc, L:/127.0.0.1:9200 - R:/127.0.0.1:61801])"m [ctx, msg]
        * @return void
        */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
//        logger.info("**接收到的基站数据<<start:" + msg.toString() +">>end");
        if(TcpClient.client.equalsIgnoreCase(msg.toString())){ //移动站
            String clinetIp = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress() + ctx.channel().id();
            logger.warn("移动站IP:" + clinetIp);
            addContext(clinetIp,ctx);
            logger.warn("if>>hashmap移动站:" + gpsServerContextHashMap);
            ctx.writeAndFlush("OK!!"); //TextWebSocketFrame
        }else{  //基站
            logger.info("else>>基站:" + msg.toString());
            logger.info("else>>hashmap基站:" + gpsServerContextHashMap);
            gpsServerContextHashMap.forEach((k,v)->{
                logger.error("基站发送给移动站:" + msg.toString());
                v.writeAndFlush(msg.toString());
            });
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("exceptionCaught! cause:" + cause.toString());
        ctx.close();
    }
}
