"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.wwebDownloadMedia = exports.wwebIsValidNumber = exports.wwebGenerateImage = exports.wwebCleanNumber = void 0;
const fs = require('fs');
const combineImage = require('combine-image');
const qr = require('qr-image');
const os = require('os');
const http_util = require('http');
const https_util = require('https');
const wwebCleanNumber = (number, full = false) => {
    number = number.replace('@s.whatsapp.net', '');
    number = !full ? `${number}@s.whatsapp.net` : `${number}`;
    return number;
};
exports.wwebCleanNumber = wwebCleanNumber;
const wwebGenerateImage = async (base64, name = 'qr.png') => {
    const PATH_QR = `${process.cwd()}/${name}`;
    let qr_svg = qr.image(base64, { type: 'png', margin: 4 });
    const writeFilePromise = () => new Promise((resolve, reject) => {
        const file = qr_svg.pipe(fs.createWriteStream(PATH_QR));
        file.on('finish', () => resolve(true));
        file.on('error', reject);
    });
    await writeFilePromise();
    const cleanImage = await combineImage([PATH_QR], {
        margin: 15,
        color: 0xffffffff,
    });
    cleanImage.write(PATH_QR);
};
exports.wwebGenerateImage = wwebGenerateImage;
const wwebIsValidNumber = (rawNumber) => {
    const regexGroup = /\@g.us\b/gm;
    const exist = rawNumber.match(regexGroup);
    return !exist;
};
exports.wwebIsValidNumber = wwebIsValidNumber;
const wwebDownloadMedia = (url) => {
    return new Promise((resolve, reject) => {
        const ext = url.split('.').pop();
        const checkProtocol = url.includes('https:');
        const handleHttp = checkProtocol ? https_util : http_util;
        const name = `tmp-${Date.now()}.${ext}`;
        const fullPath = `${os.tmpdir()}/${name}`;
        const file = fs.createWriteStream(fullPath);
        handleHttp.get(url, function (response) {
            response.pipe(file);
            file.on('finish', function () {
                file.close();
                resolve(fullPath);
            });
            file.on('error', function () {
                console.log('errro');
                file.close();
                reject(null);
            });
        });
    });
};
exports.wwebDownloadMedia = wwebDownloadMedia;
