/**
 * 华为云对象存储服务obs
 * @date 2022-08-09 11:55:58
 * @author 黄家维
 */

import { logger } from "mslib";
import path = require("path");
import { Singleton } from "typescript-ioc";
import { IocConfigProvider } from "./Config";
import Contants from "./Contants";
import { OssService } from "./OssService";

const ObsClient = require('esdk-obs-nodejs');

/**
 * 华为obs客户端实例
 * 
 * @see [huawei-obs](https://support.huaweicloud.com/api-obs_nodejs_sdk_api_zh/obs_39_0101.html)
 */
export const obsClient = new ObsClient({
    access_key_id: 'NZEGUDBCFFAXKOODXAYT',
    secret_access_key: '6idSEUUwrguY22GmmXZWIGE0LYGYTn9lyPBN2Slj',
    server: 'obs.cn-east-3.myhuaweicloud.com',
});

/**
 * 非标桶
 */
let non_standard_bucket = 'ddd-nonstandar';
let accessBaseUrl = 'http://dddfile.keytop.cn';

/**
 * 华为obs响应
 */
export class HuaWeiObsResponse {
    /**
     * 判断华为接口响应是否成功
     */
    static statusIsSuccess(status: number) {
        return status === 200;
    }

    CommonMsg: {
        Status: number,
        Code: string,
        Message: string,
        HostId: string,
        RequestId: string,
        InterfaceResult: any,
        Id2: string
    };

    InterfaceResult: {
        ContentLength: string,
        Date: string,
        Reserved: undefined,
        RequestId: string,
        Id2: string,
        ETag: string
    };
}

@Singleton
export class HuaWeiObsService implements OssService {
    getRootPath() {
        return Contants.P_ID || IocConfigProvider.getBasicConfig()?.tapdId || 'tapdId';
    }

    /**
     * 上传对象到huawei-obs
     */
    put(data: string | Buffer, name: string): Promise<string> {
        return new Promise((resolve, reject) => {
            let fullname = `${this.getRootPath()}/${name}`;

            obsClient.putObject({
                Bucket: non_standard_bucket,
                Key: fullname,
                Body: data
            }, (err: any, res: HuaWeiObsResponse) => {
                if (err) reject(err);
                if (!HuaWeiObsResponse.statusIsSuccess(res?.CommonMsg.Status)) {
                    reject(res);
                }

                let url = `${accessBaseUrl}/${fullname}`;
                logger.info(`huawei-obs 上传对象成功,对象访问地址:${url}`);

                resolve(url);
            });
        })
    }
} 