import {GatewayConfig} from "../config/GatewayConfig";
import {AuthType} from "../enums/AuthType";
import {RequestBodyType} from "../enums/RequestBodyType";
import BodyUtils from "../utils/BodyUtils";
import {sha256} from "js-sha256";
import {MsNodeType} from "../enums/MsNodeType";

export class StcHttpRequestObj {

    method: string | undefined;
    callUrl: string | undefined;
    fromNode: MsNodeType | undefined;
    toNode: MsNodeType | undefined;
    bodyContent: string | undefined;
    header = {};
    params = {};
    statusCode: number | undefined;


    constructor(config: GatewayConfig, method: string, sid: string, version: string,
                tags: string, params: object, header: object, bodyObj: object, authType: AuthType, bodyType?: RequestBodyType) {

        this.header = header
        this.params = params;


        this.method = method;
        this.header["sid"] = sid;
        this.header["version"] = version;
        this.header["tags"] = tags;
        this.header[config.headerVariableName] = config.appId;
        this.header["envCode"] = config.envCode;

        const list = []
        //RAW_JSON请求时，http协议不会对数据进行encode，所以签名也就不用encode
        BodyUtils.bodyToArr("", bodyObj, list, bodyType != RequestBodyType.RAW_JSON);
        let bodyStr = BodyUtils.arrToStr(list);
        let timestamp = Number.parseInt((new Date().getTime() / 1000).toString());
        this.header["timestamp"] = timestamp.toString();
        let sign, signSrc = "";
        switch (authType) {
            case AuthType.NONE:
                break;
            case AuthType.BASE:
                signSrc = sid + version + timestamp + config.appKey;
                break;
            case AuthType.ADVANCED:
                signSrc = sid + version + bodyStr + timestamp + config.appKey;
                break;
        }
        sign = sha256(signSrc);
        this.header["sign"] = sign;
        this.header["signSrc"] = signSrc;

        if (bodyObj != null && !BodyUtils.isPrimitiveDataTypes(bodyObj)) {
            this.bodyContent = JSON.stringify(bodyObj);
        }

    }
}