"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteObjects = exports.cosUploadByStream = exports.cosUploadByBuffer = exports.cosUpload = void 0;
const tslib_1 = require("tslib");
const cos_nodejs_sdk_v5_1 = tslib_1.__importDefault(require("cos-nodejs-sdk-v5"));
const log_1 = require("@/utils/log");
const config_1 = require("@/config");
const enum_1 = require("@/@types/enum");
const aegis_1 = require("@/utils/aegis");
const log = new log_1.Logger('cos-util');
const ErrorMsg = {
    [-1 /* ParamsMiss */]: '参数缺失（origin，passWord，filePath，stream是必填参数）',
    [-2 /* UploadStreamError */]: '上传失败（流处理异常）',
    [-3 /* UploadError */]: '上传失败',
    [-4 /* EmptyFileError */]: '文件为空, 已忽略',
};
const cosUpload = (key, buffer) => exports.cosUploadByBuffer({
    SecretId: config_1.config.cos.SecretId,
    SecretKey: config_1.config.cos.SecretKey,
    Bucket: config_1.config.cos.Bucket,
    Region: config_1.config.cos.Region,
    Key: key,
    buffer,
});
exports.cosUpload = cosUpload;
const cosUploadByBuffer = function (options) {
    const { SecretId, SecretKey, Bucket, Region, Key, buffer, StorageClass = 'STANDARD', onProgress } = options;
    const timeEnd = aegis_1.timeStart(enum_1.ReportEvent.COSUpload);
    return new Promise((resolve, reject) => {
        const client = new cos_nodejs_sdk_v5_1.default({
            SecretId,
            SecretKey,
        });
        client.putObject({
            Bucket,
            Region,
            Key,
            StorageClass,
            Body: buffer,
            onProgress: onProgress ? onProgress : () => { },
        }, (err, data) => {
            timeEnd({
                ext1: `${Math.ceil(buffer.length / 1024)}KB`,
            });
            if (err) {
                reject({
                    code: -3 /* UploadError */,
                    msg: ErrorMsg[-3 /* UploadError */],
                });
            }
            else {
                log.info('upload to cos suc, location: %s, statusCode %s', data.Location, data.statusCode);
                resolve({
                    code: 0,
                    msg: '',
                    data,
                });
            }
        });
    });
};
exports.cosUploadByBuffer = cosUploadByBuffer;
const cosUploadByStream = function (options) {
    const { SecretId, SecretKey, Bucket, Region, Key, stream, StorageClass = 'STANDARD', onProgress } = options;
    return new Promise((resolve, reject) => {
        if (Boolean(SecretId && SecretKey && Bucket && Region && Key && stream) === false) {
            reject({
                code: -1 /* ParamsMiss */,
                msg: ErrorMsg[-1 /* ParamsMiss */],
            });
            return;
        }
        const chunkArr = [];
        stream.on('data', (chunk) => {
            chunkArr.push(chunk);
        });
        stream.on('end', () => tslib_1.__awaiter(this, void 0, void 0, function* () {
            const buffer = Buffer.concat(chunkArr);
            const byteSize = buffer.byteLength;
            if (byteSize === 0) {
                reject({
                    code: -4 /* EmptyFileError */,
                    msg: ErrorMsg[-4 /* EmptyFileError */],
                });
                return;
            }
            exports.cosUploadByBuffer({
                SecretId,
                SecretKey,
                Bucket,
                Region,
                Key,
                buffer,
                StorageClass,
                onProgress,
            })
                .then(resolve)
                .catch(reject);
        }));
        stream.on('error', (err) => {
            log.error('upload cos error: %j', err);
            reject({
                code: -2 /* UploadStreamError */,
                msg: ErrorMsg[-2 /* UploadStreamError */],
            });
        });
    });
};
exports.cosUploadByStream = cosUploadByStream;
const deleteObjects = function (keys) {
    const { SecretId } = config_1.config.cos;
    const { SecretKey } = config_1.config.cos;
    const { Bucket } = config_1.config.cos;
    const { Region } = config_1.config.cos;
    const client = new cos_nodejs_sdk_v5_1.default({
        SecretId,
        SecretKey,
    });
    return new Promise((resolve, reject) => {
        client.deleteMultipleObject({
            Bucket,
            Region,
            Objects: keys.map((Key) => ({ Key })),
        }, (err, data) => {
            if (err)
                return reject(err);
            resolve(data);
        });
    });
};
exports.deleteObjects = deleteObjects;
