const tar = require('tar');
// https://www.npmjs.com/package/tar

class TarWrapper {
    /**
     * Extract tarball.
     * @param {String} source 
     * @param {String} target 
     * @param {Object} opts 
     * @param {RegExp} ignorePattern 
     * @returns {Object: Result}
     */
    static async extract(source, target, opts, ignorePattern) {
        const result = { isSuccess: true };

        await tar.extract({
            cwd: target,
            file: source,
            filter: (path, stat) => {
                if (ignorePattern.test(path)) {
                    return false;
                }

                return true;
            }
        }).catch((err) => {
            result.isSuccess = false;
            result.error = err;
        });

        return result;
    }

    /**
     * Inspect tarball to count files inside it.
     * @param {String} source 
     * @param {String} target 
     * @param {Object} opts 
     * @param {RegExp} ignorePattern 
     * @returns {Object: Result} result
     */
    static async getTarFilesCount(source, target, opts, ignorePattern) {
        const result = { isSuccess: true, data: 0 };

        await tar.list({
            file: source,
            filter: (path, stat) => {
                if (ignorePattern.test(path) || stat.type === "Directory") {
                    return false;
                }

                return true;
            },
            onentry: (entry => {
                result.data++;
            })
        }).catch((err) => {
            result.isSuccess = false;
            result.error = err;
        });

        return result;
    }
}

module.exports = TarWrapper;
