import { Container } from 'typescript-ioc';
import { AliOssService } from './AliOss';

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

Container.bind(OssService).to(AliOssService);

/**
 * 上传base64到`OSS`服务器
 * 
 * ```
 * import { downloadFile, putBase64File, CryptoUtils, uuid } from "refs/nslib";
 * 
 * let buf = await downloadFile('https://image-cn.keytop.cn/452/172.19.2.6/2022/08/25/20220825143509132_172.19.2.6_024231.jpg');
 * let url = await putBase64File(CryptoUtils.base64Encode(buf), `${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`服务
 * 
 * ```
 * import { downloadFile, putFile, uuid } from "refs/nslib";
 * 
 * let buf = await downloadFile('https://image-cn.keytop.cn/452/172.19.2.6/2022/08/25/20220825143509132_172.19.2.6_024231.jpg');
 * let url = await putFile(buf, `${uuid()}.jpg`);
 * ```
 * @param name 对象名
 * @return 对象地址
 */
export async function putFile(data: string | Buffer, name: string): Promise<string> {
    let service = Container.get(OssService);
    return await service.put(data, name);
}