"use strict";
/*
 * Tencent is pleased to support the open source community by making
 * Hippy available.
 *
 * Copyright (C) 2017-2019 THL A29 Limited, a Tencent company.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
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("@debug-server-next/utils/log");
const config_1 = require("@debug-server-next/config");
const enum_1 = require("@debug-server-next/@types/enum");
const report_1 = require("@debug-server-next/utils/report");
const log = new log_1.Logger('cos-util');
const baseCosOption = {
    Domain: '{Bucket}.cos-internal.{Region}.tencentcos.cn',
};
const ErrorMsg = {
    [-1 /* COSErrorCode.ParamsMiss */]: 'miss params (origin，passWord，filePath，stream are required fields)',
    [-2 /* COSErrorCode.UploadStreamError */]: 'upload fail (stream error)',
    [-3 /* COSErrorCode.UploadError */]: 'upload fail',
    [-4 /* COSErrorCode.EmptyFileError */]: 'empty file is ignored',
};
const cosUpload = (key, buffer) => (0, 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 = report_1.report.timeStart(enum_1.ReportEvent.COSUpload);
    return new Promise((resolve, reject) => {
        const client = new cos_nodejs_sdk_v5_1.default({
            ...baseCosOption,
            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 /* COSErrorCode.UploadError */,
                    msg: ErrorMsg[-3 /* COSErrorCode.UploadError */],
                });
            }
            else {
                log.verbose('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 /* COSErrorCode.ParamsMiss */,
                msg: ErrorMsg[-1 /* COSErrorCode.ParamsMiss */],
            });
            return;
        }
        const chunkArr = [];
        stream.on('data', (chunk) => {
            chunkArr.push(chunk);
        });
        // eslint-disable-next-line @typescript-eslint/no-misused-promises
        stream.on('end', async () => {
            const buffer = Buffer.concat(chunkArr);
            const byteSize = buffer.byteLength;
            if (byteSize === 0) {
                reject({
                    code: -4 /* COSErrorCode.EmptyFileError */,
                    msg: ErrorMsg[-4 /* COSErrorCode.EmptyFileError */],
                });
                return;
            }
            (0, 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 /* COSErrorCode.UploadStreamError */,
                msg: ErrorMsg[-2 /* COSErrorCode.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({
        ...baseCosOption,
        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;
