import {UserInfo} from "../user/UserInfo";
import UserInfoParser from "../user/UserInfoParser";
import {logger} from "../mslib";

export class MeHeader {
    /**
     * 微服务项目ID
     * cn.aa.bb.ProjectA
     */
    pid: string = "";

    /**
     * 微服务ID
     * $pid.$serviceCode
     *
     * cn.aa.bb.ProjectA.Pay
     */
    sid: string = "";

    /**
     * 微服务项目次版本号
     * 1.0
     */
    version: string = "";

    /**
     * 用户Token
     */
    userToken: string = "";

    /**
     * 用户域
     */
    userDomain: string = "";

    /**
     * Kong解析后的用户ID
     */
    kongUserId: string = "";

    /**
     * Kong用户信息Base64字符串
     */
    kongUserInfoBase64: string = "";

    static parse(httpHeaders: any): MeHeader {
        let result = new MeHeader();
        if (httpHeaders != null) {
            result.pid = httpHeaders["pid"] || "";
            result.sid = httpHeaders["sid"] || "";
            result.version = httpHeaders["version"] || "";
            result.userToken = httpHeaders["user-token"] || "";
            result.userDomain = httpHeaders["user-domain"] || "";
            result.kongUserId = httpHeaders["kong-user-id"] || "";
            result.kongUserInfoBase64 = httpHeaders["kong-user-base64"] || "";
        }
        return result;
    }

    static parseUserInfo(meHeader): UserInfo {
        let userInfo: UserInfo = undefined
        try {
            if (meHeader.kongUserInfoBase64) {
                userInfo = UserInfoParser.parse(meHeader.kongUserInfoBase64)
            }
        } catch (e) {
            logger.error("Parser user info error :", e);
        }
        return userInfo
    }

    toString(): string {
        return JSON.stringify(this)
    }
}
