package net.northking.cctp.upperComputer.driver.usbmuxd.payload.usbmuxd.request;

import com.dd.plist.NSDictionary;
import com.dd.plist.NSNumber;
import net.northking.cctp.upperComputer.driver.usbmuxd.AppleDevice;
import net.northking.cctp.upperComputer.driver.usbmuxd.payload.usbmuxd.UsbMuxdPayload;


/**
 * 请求连接到设备内部程序监听的本地端口
 */
public class ConnectDevicePortRequest extends UsbMuxdPayload {

    /**
     * 要连接的设备信息
     */
    public final AppleDevice appleDevice;

    /**
     * 经过处理的端口号，传递给设备
     */
    public final int encodePort;

    /**
     * 要连接的端口号
     */
    public final int port;

    /**
     * 持有根节点数据
     */
    private final NSDictionary root = new NSDictionary();

    /**
     * @param appleDevice 要连接的设备
     * @param port        要连接的端口号
     */
    public ConnectDevicePortRequest(AppleDevice appleDevice, int port) {
        this.appleDevice = appleDevice;
        this.port = port;
        this.encodePort = swapPortNumber(port);

        root.put("DeviceID", new NSNumber(appleDevice.getConnectionDetail().deviceId));
        root.put("MessageType", "Connect");
        root.put("PortNumber", new NSNumber(this.encodePort));
        root.put("ProgName", PROG_NAME);
    }


    /**
     * 处理原始端口号，用于作为参数传递到设备上<br>
     * 苹果设备内传递端口号参数时都经过额外的处理<br>
     * 高低位交换
     *
     * @param port 原始端口号
     * @return 加工过的端口号
     */
    protected static int swapPortNumber(int port) {
        return ((port << 8) & 0xFF00) | (port >> 8);
    }

    @Override
    public NSDictionary toData() {
        return root;
    }
}
