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

import com.dd.plist.NSDictionary;
import com.dd.plist.NSNumber;
import com.dd.plist.NSString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 普通请求结果响应<br>
 * REST风格
 */

public class ResultResponse {

    /**
     * 响应消息类型
     */
    public final String messageType;

    /**
     * 响应代码
     */
    public final int number;

    /**
     * 错误信息<br>
     * 如果没有错误，则为null
     */
    public final String error;

    private Logger log = LoggerFactory.getLogger(ResultResponse.class);

    public ResultResponse(NSDictionary nsDictionary) {
        if (!nsDictionary.containsKey("MessageType")) {
            String errorText = "无法读取usbmuxd响应结果，缺少MessageType";
            log.error(errorText);
            throw new IllegalArgumentException(errorText);
        }
        if (!(nsDictionary.get("MessageType") instanceof NSString)) {
            String errorText = "无法读取usbmuxd响应结果，键MessageType对应的类型不为NSString";
            log.error(errorText);
            throw new IllegalArgumentException(errorText);
        }
        NSString messageTypeString = (NSString) nsDictionary.get("MessageType");
        messageType = messageTypeString.getContent();

        if (nsDictionary.containsKey("Error")) {
            if (!(nsDictionary.get("Error") instanceof NSString)) {
                String errorText = "无法读取usbmuxd响应结果，键Error对应的类型不为NSString";
                log.error(errorText);
                throw new IllegalArgumentException(errorText);
            }
            NSString errorString = (NSString) nsDictionary.get("Error");
            error = errorString.getContent();
        } else {
            error = null;
        }

        if (!nsDictionary.containsKey("Number")) {
            String errorText = "无法读取usbmuxd响应结果，缺少Number";
            log.error(errorText);
            throw new IllegalArgumentException(errorText);
        }
        if (!(nsDictionary.get("Number") instanceof NSNumber)) {
            String errorText = "无法读取usbmuxd响应结果，键Number对应的类型不为NSNumber";
            log.error(errorText);
            throw new IllegalArgumentException(errorText);
        }
        NSNumber numberNumber = (NSNumber) nsDictionary.get("Number");
        number = numberNumber.intValue();
    }

    /**
     * 简单判断是否为成功响应
     *
     * @return 是否成功
     */
    public boolean isSuccess() {
        return number == 0;
    }

}
