package com.zt.plat.module.qms.iot.tcpserver.proxy;

/**
 * <b>ProxyProtocolMessage</b>
 * 代理协议
 * <p>
 * 更新历史：
 * <pre> 版本         更新时间            更新者        更新内容<hr/>
 * V1.0      2024年9月10日          wxr         Add</pre>
 * <b>Copyright (C)  云南志者竟成科技有限公司</b> 
 * </p>
 * @author 王兴荣<wxr@wangxingrong.com>
 * @version V1.0 
 * @since 2024年9月10日
 */
public class ProxyProtocolMessage {

	/**
	 * 代理的协议，ipv4/6
	 */
	private final String protocol;
	/**
	 * 源地址
	 */
	private final String sourceAddress;
	/**
	 * 目标地址
	 */
	private final String destinationAddress;
	/**
	 * 源端口
	 */
	private final int sourcePort;
	/**
	 * 目标端口
	 */
	private final int destinationPort;

	public ProxyProtocolMessage(String protocol,
								String sourceAddress,
								String destinationAddress,
								String sourcePort,
								String destinationPort) {
		this(protocol, sourceAddress, destinationAddress, portStringToInt(sourcePort), portStringToInt(destinationPort));
	}

	public ProxyProtocolMessage(String protocol,
								String sourceAddress,
								String destinationAddress,
								int sourcePort,
								int destinationPort) {
		this.protocol = protocol;
		this.sourceAddress = sourceAddress;
		this.destinationAddress = destinationAddress;
		this.sourcePort = sourcePort;
		this.destinationPort = destinationPort;
	}

	public String getProtocol() {
		return protocol;
	}

	public String getSourceAddress() {
		return sourceAddress;
	}

	public String getDestinationAddress() {
		return destinationAddress;
	}

	public int getSourcePort() {
		return sourcePort;
	}

	public int getDestinationPort() {
		return destinationPort;
	}

	/**
	 * Convert port to integer
	 *
	 * @param value the port
	 * @return port as an integer
	 * @throws IllegalArgumentException if port is not a valid integer
	 */
	private static int portStringToInt(String value) {
		int port;
		try {
			port = Integer.parseInt(value);
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("invalid port: " + value, e);
		}
		if (port <= 0 || port > 65535) {
			throw new IllegalArgumentException("invalid port: " + value + " (expected: 1 ~ 65535)");
		}
		return port;
	}

	@Override
	public String toString() {
		return "ProxyProtocolMessage{" +
			"message='" + protocol + '\'' +
			", sourceAddress='" + sourceAddress + '\'' +
			", destinationAddress='" + destinationAddress + '\'' +
			", sourcePort=" + sourcePort +
			", destinationPort=" + destinationPort +
			'}';
	}
}
