var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
/**
 * Copyright (C) 2024 Hedera Hashgraph, LLC
 *
 * 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.
 *
 */
import { SoloError, IllegalArgumentError, MissingArgumentError } from './errors.js';
import fs from 'fs';
import AdmZip from 'adm-zip';
import * as tar from 'tar';
import chalk from 'chalk';
import path from 'path';
import { SoloLogger } from './logging.js';
import { inject, injectable } from 'tsyringe-neo';
import { patchInject } from './container_helper.js';
let Zippy = class Zippy {
    logger;
    constructor(logger) {
        this.logger = logger;
        this.logger = patchInject(logger, SoloLogger, this.constructor.name);
    }
    /**
     * Zip a file or directory
     * @param srcPath - path to a file or directory
     * @param destPath - path to the output zip file
     * @param [verbose] - if true, log the progress
     * @returns path to the output zip file
     */
    async zip(srcPath, destPath, verbose = false) {
        if (!srcPath)
            throw new MissingArgumentError('srcPath is required');
        if (!destPath)
            throw new MissingArgumentError('destPath is required');
        if (!destPath.endsWith('.zip'))
            throw new MissingArgumentError('destPath must be a path to a zip file');
        try {
            const zip = new AdmZip('', {});
            const stat = fs.statSync(srcPath);
            if (stat.isDirectory()) {
                zip.addLocalFolder(srcPath, '');
            }
            else {
                zip.addFile(path.basename(srcPath), fs.readFileSync(srcPath), '', stat);
            }
            await zip.writeZipPromise(destPath, { overwrite: true });
            return destPath;
        }
        catch (e) {
            throw new SoloError(`failed to unzip ${srcPath}: ${e.message}`, e);
        }
    }
    unzip(srcPath, destPath, verbose = false) {
        const self = this;
        if (!srcPath)
            throw new MissingArgumentError('srcPath is required');
        if (!destPath)
            throw new MissingArgumentError('destPath is required');
        if (!fs.existsSync(srcPath))
            throw new IllegalArgumentError('srcPath does not exists', srcPath);
        try {
            const zip = new AdmZip(srcPath, { readEntries: true });
            zip.getEntries().forEach(zipEntry => {
                if (verbose) {
                    self.logger.debug(`Extracting file: ${zipEntry.entryName} -> ${destPath}/${zipEntry.entryName} ...`, {
                        src: zipEntry.entryName,
                        dst: `${destPath}/${zipEntry.entryName}`,
                    });
                }
                zip.extractEntryTo(zipEntry, destPath, true, true, true, zipEntry.entryName);
                if (verbose) {
                    self.logger.showUser(chalk.green('OK'), `Extracted: ${zipEntry.entryName} -> ${destPath}/${zipEntry.entryName}`);
                }
            });
            return destPath;
        }
        catch (e) {
            throw new SoloError(`failed to unzip ${srcPath}: ${e.message}`, e);
        }
    }
    tar(srcPath, destPath) {
        if (!srcPath)
            throw new MissingArgumentError('srcPath is required');
        if (!destPath)
            throw new MissingArgumentError('destPath is required');
        if (!destPath.endsWith('.tar.gz'))
            throw new MissingArgumentError('destPath must be a path to a tar.gz file');
        if (!fs.existsSync(srcPath))
            throw new IllegalArgumentError('srcPath does not exists', srcPath);
        try {
            tar.c({
                gzip: true,
                file: destPath,
                sync: true,
            }, [srcPath]);
            return destPath;
        }
        catch (e) {
            throw new SoloError(`failed to tar ${srcPath}: ${e.message}`, e);
        }
    }
    untar(srcPath, destPath) {
        if (!srcPath)
            throw new MissingArgumentError('srcPath is required');
        if (!destPath)
            throw new MissingArgumentError('destPath is required');
        if (!fs.existsSync(srcPath))
            throw new IllegalArgumentError('srcPath does not exists', srcPath);
        if (!fs.existsSync(destPath)) {
            fs.mkdirSync(destPath);
        }
        try {
            tar.x({
                C: destPath,
                file: srcPath,
                sync: true,
            });
            return destPath;
        }
        catch (e) {
            throw new SoloError(`failed to untar ${srcPath}: ${e.message}`, e);
        }
    }
};
Zippy = __decorate([
    injectable(),
    __param(0, inject(SoloLogger)),
    __metadata("design:paramtypes", [SoloLogger])
], Zippy);
export { Zippy };
//# sourceMappingURL=zippy.js.map