package com.pqs9900.serviceImpl.configuration;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.pqs9900.controller.webtool.CsvDataController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.njcn.mapper.configuration.DeviceMapper;
import com.njcn.mapper.configuration.PushInfoMapper;
import com.njcn.utils.PubUtils;
import com.pqs9900.service.configuration.PushNodeService;

@Service
public class PushNodeServiceImpl implements PushNodeService {
	private static final Logger logger = LoggerFactory.getLogger(PushNodeServiceImpl.class);
	@Autowired
	private DeviceMapper deviceMapper;

	@Autowired
	private PushInfoMapper pushinfoMapper;

	@Override
	public List<String> getNodes() {
		return deviceMapper.getPushNodes();
	}

	@Override
	public String sentSocket(String message, String nodeIp) {
		String result = null;
		// 与服务端建立连接
		Socket socket = null;
		InputStream is = null;
		BufferedReader din;
		OutputStream outputStream=null;
		try {
			// 读取配置文件
			Properties pros = PubUtils.readProperties(getClass().getClassLoader(),"java.properties");

			int port = Integer.valueOf(pros.get("SOCKETPORT").toString());
			socket = new Socket(nodeIp, port);
			outputStream= socket.getOutputStream();
			socket.getOutputStream().write(message.getBytes("UTF-8"));
			is = socket.getInputStream();
			din = new BufferedReader(new InputStreamReader(is));
			char[] cbuf = new char[1024];
			din.read(cbuf);
			result = new String(cbuf);
		} catch (IOException e) {
			logger.error("产生了异常，异常是"+e.getMessage());
		} finally {
			try{
				if(null!=is){
					is.close();
				}
			}catch(Exception e){
				logger.error("关闭流异常，异常为："+e.toString());
			}
			try{
				if(null!=socket){
					socket.close();
				}
			}catch(Exception e){
				logger.error("关闭流异常，异常为："+e.toString());
			}
			try{
				if(null!=outputStream){
					outputStream.close();
				}
			}catch(Exception e){
				logger.error("关闭流异常，异常为："+e.toString());
			}

		}
		return result;
	}

	public void delByNodeIP(String nodeIp) {
		try {
			int flag = pushinfoMapper.delByIP(nodeIp);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}