package net.northking.cctp.upperComputer.driver.usbmuxd.service;

import com.dd.plist.NSDictionary;
import com.dd.plist.NSObject;
import net.northking.cctp.upperComputer.driver.usbmuxd.AppleDevice;
import net.northking.cctp.upperComputer.driver.usbmuxd.UsbMuxd;
import net.northking.cctp.upperComputer.driver.usbmuxd.payload.service.request.GetValueRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 与Apple设备内部的Lockdown服务通信
 */
public class LockdownService extends AppleDeviceInnerService {

    private final Logger logger = LoggerFactory.getLogger(LockdownService.class);
    public static final int PORT = 62078;
    public LockdownService(UsbMuxd usbMuxd, AppleDevice appleDevice) throws IOException {
        super(usbMuxd, appleDevice);
        connectOperator = usbMuxd.connectDeviceLocalPort(appleDevice, PORT);

    }

    @Override
    public int getPort() {
        return PORT;
    }

    public String queryValue(ValueName valueName) {
        GetValueRequest request = new GetValueRequest();
        request.setTarget(valueName);
        try {
            write(request);
        } catch (IOException e) {
            logger.error("向设备" + appleDevice.getConnectionDetail().serialNumber + "的lockdown服务查询" + valueName + "时发生IO异常", e);
            return null;
        }
        try {
            NSDictionary result = read();
            NSObject value = result.get("Value");
            if (value != null) {
                return value.toString();
            }
        } catch (IOException e) {
            logger.error("向设备" + appleDevice.getConnectionDetail().serialNumber + "的lockdown服务查询" + valueName + "后读取时发生IO异常", e);
        }
        return null;
    }

    public enum ValueName {
        DEVICE_NAME("DeviceName"),
        PRODUCT_TYPE("ProductType"),
        PRODUCT_VERSION("ProductVersion"),
        DEVICE_PUBLIC_KEY("DevicePublicKey"),
        WIFI_ADDRESS("WiFiAddress");
        final String name;

        ValueName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }
}
