import StringUtils from "./StringUtils";

class BodyUtils {

    bodyToArr(key: string, obj: any, toArr: Array<string>, encode: boolean): Array<string> {
        if (null == obj) {
            return toArr;
        }
        if (this.isPrimitiveDataTypes(obj)) {
            if (StringUtils.isNotEmpty(obj)) {
                let value = obj.toString()
                if (encode) {
                    value = encodeURI(value)
                }
                toArr.push(key + "=" + value);
            }
            return toArr;
        }
        if (Array.isArray(obj)) {
            if (obj.length == 0) {
                return toArr;
            }
            const objects = obj as Array<any>;

            if (this.isPrimitiveDataTypes(obj[0])) {
                if (StringUtils.isNotEmpty(key)) {
                    toArr.push(key + "=" + this.join("", objects));
                } else {
                    toArr.push(this.join("", objects));
                }
                return toArr;
            }

            for (let i = 0; i < objects.length; i++) {
                let o = objects[i];
                if (StringUtils.isNotEmpty(key)) {
                    this.bodyToArr(key + "." + i, o, toArr, encode);
                } else {
                    this.bodyToArr(i.toString(), o, toArr, encode);
                }
            }
            return toArr;
        }

        for (let attr in obj) {
            if (StringUtils.isNotEmpty(key)) {
                this.bodyToArr(key + "." + attr.toString(), obj[attr], toArr, encode);
            } else {
                this.bodyToArr(attr.toString(), obj[attr], toArr, encode);
            }
        }
        return toArr
    }


    /**
     * 数组拼接成字符串
     * @param arr
     * @return
     */
    private join(delimiter: string, arr: Array<any>): string {
        return arr.join(delimiter)
    }

    /**
     * 数组根据ASCII排序，并拼接成字符串
     * @param arr
     * @return
     */
    arrToStr(arr: Array<String>): string {
        if (null == arr || arr.length == 0) {
            return "";
        }
        arr.sort()
        return arr.join("&")
    }

    /**
     * 是否基础数据类型判断
     * @param obj
     */
    isPrimitiveDataTypes(obj: Object): boolean {
        return !(typeof obj === 'object')
    }
}


export default new BodyUtils()