package com.gyee.frame.netty.websocket.secureecho;

import com.alibaba.fastjson.JSON;
import com.gyee.frame.common.spring.InitialRunner;
import com.gyee.frame.common.spring.SpringUtils;
import com.gyee.frame.model.auto.Weatherfd;
import com.gyee.frame.model.auto.Weatherfh;
import com.gyee.frame.service.WeatherfdService;
import com.gyee.frame.service.WeatherfhService;
import com.gyee.frame.util.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.List;
/**
 * Echo Client Handler.
 * 
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

	private WeatherfdService weatherfdService = SpringUtils.getBean("weatherfdService");
	private WeatherfhService weatherfhService = SpringUtils.getBean("weatherfhService");

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {



		ByteBuf in = (ByteBuf) msg;
		String str=in.toString(CharsetUtil.UTF_8);
		String [] strs=str.split("\\|");
		if(StringUtils.isNotNull(strs))
		{
			if(StringUtils.isNotNull(strs) && strs.length==2)
			{
				if(strs[0].equals("Weatherfd"))
				{
					String value=strs[1];
					List<Weatherfd> list= (List<Weatherfd>)JSON.parseArray(value,Weatherfd.class);

					if(!list.isEmpty())
					{
						for(Weatherfd weatherfd:list)
						{
							weatherfd.setId(null);
							weatherfdService.insertSelective(weatherfd);
						}
					}
				}else if(strs[0].equals("Weatherfh"))
				{
					String value=strs[1];
					List<Weatherfh> list= (List<Weatherfh>)JSON.parseArray(value,Weatherfh.class);

					if(!list.isEmpty())
					{
						for(Weatherfh weatherfh:list)
						{
							weatherfh.setId(null);
							weatherfhService.insertSelective(weatherfh);
						}
					}
				}
			}

			InitialRunner.status=1;

		}

		// 接收服务器的信息并打印到控制台
//		ByteBuf in = (ByteBuf) msg;
//		String str=in.toString(CharsetUtil.UTF_8);
//		String [] strs=str.split(";");
//		if(StringUtils.isNotNull(strs))
//		{
//			String type=strs[0];
//			String obj=strs[1];
////			System.out.println(ctx.channel().remoteAddress() + " -> Client :" +
////					sb.toString());
//			if(type.equals("inital"))
//			{
//				try {
//					weatherfdService.deleteDays();
//				} catch (ParseException e) {
//					e.printStackTrace();
//				}
//			}else	if(type.equals("weatherfd")  && strs.length==2)
//			{
//				Weatherfd weatherfd= (Weatherfd)JSON.parse(obj);
//				weatherfd.setId(null);
//				weatherfdService.insertSelective(weatherfd);
//			}
//		}




	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

		// 当出现异常就关闭连接
		cause.printStackTrace();
		ctx.close();
	}
}