import { Stream } from 'stream';
import { Container } from 'typescript-ioc';
import { AliOssService } from './AliOss';
import { HuaWeiObsService } from './HuaWeiObs';

/**
 * OSS 对象存储服务(Object Storage Service)
 */
export abstract class OssService {
    abstract put(data: string | Buffer | Stream, name: string): Promise<string>;
}

if (process.env['KT_CLOUD_TYPE']?.toLocaleUpperCase() == 'HUAWEI') {
    Container.bind(OssService).to(HuaWeiObsService);
} else {
    Container.bind(OssService).to(AliOssService);
}

/**
 * 上传base64到`OSS`服务器
 * 
 * **注：华为云容器(process.env['KT_CLOUD_TYPE']?.toLocaleUpperCase() == 'HUAWEI')自动使用华为obs服务，非华为云容器使用ali-oss服务**
 * ```
 * import { downloadFile2Base64, putBase64File, uuid } from "refs/nslib";
 * 
 * let base64 = await downloadFile2Base64('https://image-cn.keytop.cn/452/172.19.2.6/2022/08/25/20220825143509132_172.19.2.6_024231.jpg');
 * let url = await putBase64File(base64, `${uuid()}.jpg`);
 * ```
 * @param data base64字符串
 * @param name 对象名
 * @return 对象访问地址
 * @throw {@link Error}
 */
export async function putBase64File(data: string, name: string) {
    let buf = null;

    //data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAA
    if (data.startsWith('data:')) {
        buf = Buffer.from(data.split(',')[1], 'base64');
    } else {
        buf = Buffer.from(data, 'base64');
    }

    return await putFile(buf, name);
}

/**
 * 上传对象到`OSS`服务
 * 
 * **注：华为云容器(process.env['KT_CLOUD_TYPE']?.toLocaleUpperCase() == 'HUAWEI')自动使用华为obs服务，非华为云容器使用ali-oss服务**
 * 
 * ```
 * import { downloadFileStream, putFile, uuid } from "refs/nslib";
 * 
 * let stream = await downloadFileStream('https://image-cn.keytop.cn/452/172.19.2.6/2022/08/25/20220825143509132_172.19.2.6_024231.jpg');
 * let url = await putFile(stream, `${uuid()}.jpg`);
 * ```
 * @param name 对象名
 * @return 对象地址
 */
export async function putFile(data: string | Buffer | Stream, name: string): Promise<string> {
    let service = Container.get(OssService);
    return await service.put(data, name);
}