package com.yeejoin.amos.iec104.business.controller;

import java.util.Date;

import com.yeejoin.amos.connect.dao.entity.ClientListenVo;
import com.yeejoin.amos.connect.dao.entity.ConfigVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yeejoin.amos.iec104.business.param.ClientParam;
import com.yeejoin.amos.iec104.business.service.intfc.IClientListenService;
import com.yeejoin.amos.iec104.business.service.intfc.IConfService;
import com.yeejoin.amos.iec104.tcp.TcpServer;
import com.yeejoin.amos.iec104.tcp.client.IEC104ClientManager;
import com.yeejoin.amos.iec104.utils.NetUtil;
import com.yeejoin.amos.op.core.common.response.CommonResponse;
import com.yeejoin.amos.op.core.util.CommonResponseUtil;
import com.yeejoin.amos.security.authorization.Authorization;

import io.swagger.annotations.Api;

@RestController
@RequestMapping(value = "/iec")
@Api(tags="客户端api")
public class ClientController  extends BaseController{
	private final Logger log = LoggerFactory.getLogger(ClientController.class);
	
	@Autowired
	IEC104ClientManager clientManager;
	
	@Autowired
	IConfService confService;
	
	@Autowired
	IClientListenService clientListenService;
	@Autowired
	TcpServer tcpServer;
	
	@PostMapping(value="/create",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse createClient(@RequestBody ClientParam client) {
		try {
			String no = confService.getMaxNo();
			ConfigVo vo = new ConfigVo();
			vo.setIp(client.getIp());
			vo.setPort(client.getPort());
			vo.setCommonAddress(client.getCommonAddress());
			vo.setIsDelete(0);
			vo.setLastUpdateTime(new Date());
			vo.setServiceType(client.getServiceType());
			vo.setServiceId(String.format("S%06d", Integer.valueOf(no)+1));
			vo.setChannelNo(String.format("N%06d", Integer.valueOf(no)+1));
			vo.setName(client.getName());
			if ("IEC_CLIENT".equals(vo.getServiceType())) {
				if (NetUtil.isLoclePortUsing(Integer.valueOf(client.getPort()))) {
					return CommonResponseUtil.failure("端口已经被占用");
				}
			}
			confService.add(vo);
			if ("IEC_SERVER".equals(vo.getServiceType())) {
				clientManager.createClient(vo.getIp(), vo.getPort(), vo.getCommonAddress());
			} else if ("IEC_CLIENT".equals(vo.getServiceType())) {
				tcpServer.createIecService(vo.getId(), vo.getPort());
			}
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("创建客户端失败");
		}
	}
	
	@PostMapping(value="/save",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse save(@RequestBody ConfigVo vo) {
		try {
			if (ObjectUtils.isEmpty(vo)) {
				return CommonResponseUtil.failure("参数错误");
			}
			if ("IEC_SERVER".equals(vo.getServiceType()) && !ObjectUtils.isEmpty(vo.getId())) {
				clientManager.closeClient(vo.getIp(), vo.getPort());
			}
			
			ConfigVo oldVo = confService.getServerById(vo.getId());
			confService.add(vo);
			if ("IEC_SERVER".equals(vo.getServiceType())) {
				clientManager.createClient(vo.getIp(), vo.getPort(), vo.getCommonAddress());
			}
			if ("IEC_CLIENT".equals(vo.getServiceType())) {
				if (oldVo.getPort().equals(vo.getPort())) {
					tcpServer.closeIecService(vo.getId());
					tcpServer.createIecService(vo.getId(), vo.getPort());
				} else {
					if (NetUtil.isLoclePortUsing(Integer.valueOf(vo.getPort()))) {
						return CommonResponseUtil.failure("端口已经被占用");
					}
					tcpServer.createIecService(vo.getId(), vo.getPort());
				}
			}
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("创建客户端失败");
		}
	}
	
	@GetMapping(value="/getAllClient",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse getAllClients() {
		try {			
			return CommonResponseUtil.success(confService.getServerByType("IEC_CLIENT"));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("创建客户端失败");
		}
	}
	
	@GetMapping(value="/getAllService",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse getAllService() {
		try {			
			return CommonResponseUtil.success(confService.getServerByType("IEC_SERVER"));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("创建客户端失败");
		}
	}
	
	@GetMapping(value="/client/{serviceId}",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse getService(@PathVariable("serviceId") String serviceId) {
		try {			
			return CommonResponseUtil.success(confService.getServerByServiceId(serviceId));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("客户端详情获取失败");
		}
	}
	
	@GetMapping(value="/subscriber/{serviceId}",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse getSubscriber(@PathVariable("serviceId") String serviceId) {
		try {			
			return CommonResponseUtil.success(clientListenService.getDataByServiceId(serviceId));
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure(e.getMessage());
		}
	}
	
	@PostMapping(value="/subscriber/add",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse addSubscriber(@RequestBody ClientListenVo listener) {
		try {
			clientListenService.add(listener);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure(e.getMessage());
		}
	}
	
	@DeleteMapping(value="/subscriber/delete/{id}",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse deleteSubscriber(@PathVariable("id") Long id) {
		try {
			clientListenService.del(id);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure(e.getMessage());
		}
	}
	
	@PutMapping(value="/subscriber/update",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse updateSubscriber(@RequestBody ClientListenVo listener) {
		try {
			clientListenService.add(listener);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure(e.getMessage());
		}
	}
	
	@PostMapping(value="/close",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse closeClient(@RequestBody ConfigVo vo) {
		try {
			confService.delete(vo.getId());
			clientManager.closeClient(vo.getIp(), vo.getPort());
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("关闭客户端失败");
		}
	}
	
	@DeleteMapping(value="/delete/{id}",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse deleteClient(@PathVariable("id") Long id) {
		try {
			ConfigVo vo = confService.findById(id);
			if ("IEC_SERVER".equals(vo.getServiceType())) {
				clientManager.closeClient(vo.getIp(), vo.getPort());
			} else {
				tcpServer.closeIecService(vo.getId());
			}
			confService.delete(id);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure(e.getMessage());
		}
	}
	
	@PostMapping(value="/reset",produces = "application/json;charset=UTF-8")
	@Authorization(ingore=true)
	public CommonResponse reset() {
		try {

			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("关闭客户端失败");
		}
	}
}
