"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebWhatsappProvider = void 0;
const mime = __importStar(require("mime-types"));
const lib_1 = require("../../../baileys/lib");
const wa_1 = require("./bot-whatsapp/wa");
const utils_whatsapp_1 = require("./utils.whatsapp");
const { createWriteStream, rename } = require("fs");
const http = require("http");
const https = require("https");
const { tmpdir } = require("os");
const mimeDep = require("mime-types");
const fileTypeFromFile = async (response) => {
    var _a;
    const type = (_a = response.headers["content-type"]) !== null && _a !== void 0 ? _a : null;
    const ext = mimeDep.extension(type);
    return {
        type,
        ext,
    };
};
const generalDownload = async (url) => {
    const handleDownload = () => {
        const checkProtocol = url.includes("https:");
        const handleHttp = checkProtocol ? https : http;
        const name = `tmp-${Date.now()}-dat`;
        const fullPath = `${tmpdir()}/${name}`;
        const file = createWriteStream(fullPath);
        return new Promise((res, rej) => {
            handleHttp.get(url, function (response) {
                response.pipe(file);
                file.on("finish", async function () {
                    file.close();
                    res({ response, fullPath });
                });
                file.on("error", function () {
                    file.close();
                    rej(null);
                });
            });
        });
    };
    const handleFile = (pathInput, ext) => new Promise((resolve, reject) => {
        const fullPath = `${pathInput}.${ext}`;
        rename(pathInput, fullPath, (err) => {
            if (err)
                reject(null);
            resolve(fullPath);
        });
    });
    const httpResponse = await handleDownload();
    const { ext } = await fileTypeFromFile(httpResponse.response);
    const getPath = await handleFile(httpResponse.fullPath, ext);
    return getPath;
};
class WebWhatsappProvider {
    constructor(sessionId) {
        this.sendButtons = async (type, number, message, buttons) => {
            const exists = await (0, wa_1.jidExists)(this.session, number, type);
            if (!exists) {
                return Error("JID does not exists");
            }
            return this.session.sendMessage(number, { text: message, buttons }, {});
        };
        this.sendText = async (type, number, message) => {
            const exists = await (0, wa_1.jidExists)(this.session, number, type);
            if (!exists) {
                return Error("JID does not exists");
            }
            return await this.session.sendMessage(number, message, {});
        };
        this.sendImage = async (type, number, url, caption) => {
            const exists = await (0, wa_1.jidExists)(this.session, number, type);
            if (!exists) {
                return Error("JID does not exists");
            }
            return this.session.sendMessage(number, { image: { url }, caption }, {});
        };
        this.sendAudio = async (type, number, url, caption) => {
            const exists = await (0, wa_1.jidExists)(this.session, number, type);
            if (!exists) {
                return Error("JID does not exists");
            }
            return this.session.sendMessage(number, { audio: { url }, caption }, {});
        };
        this.sendVideo = async (type, number, url, caption) => {
            const exists = await (0, wa_1.jidExists)(this.session, number, type);
            if (!exists) {
                return Error("JID does not exists");
            }
            return this.session.sendMessage(number, { video: { url }, caption }, {});
        };
        this.sendFile = async (type, number, url, caption) => {
            const exists = await (0, wa_1.jidExists)(this.session, number, type);
            if (!exists) {
                return Error("JID does not exists");
            }
            const mimetype = mime.lookup(url);
            return this.session.sendMessage(number, { document: { url }, mimetype, caption }, {});
        };
        this.sendMedia = async (type, number, mediaUrl, text) => {
            const exists = await (0, wa_1.jidExists)(this.session, number, type);
            if (!exists) {
                return Error("JID does not exists");
            }
            await this.session.presenceSubscribe(number);
            await (0, lib_1.delay)(500);
            await this.session.sendPresenceUpdate("composing", number);
            await (0, lib_1.delay)(700);
            await this.session.sendPresenceUpdate("paused", number);
            const mimeType = mime.lookup(mediaUrl);
            if (mimeType.includes("image")) {
                return this.sendImage(type, number, mediaUrl, text);
            }
            if (mimeType.includes("video")) {
                return this.sendVideo(type, number, mediaUrl, text);
            }
            if (mimeType.includes("audio")) {
                return this.sendAudio(type, number, mediaUrl, text);
            }
            return this.sendFile(type, number, mediaUrl, text);
        };
        this.sendMessage = async (userId, message, options = { type: "number" }) => {
            var _a, _b, _c;
            const number = userId !== "status@broadcast"
                ? (0, utils_whatsapp_1.wwebCleanNumber)(userId)
                : "status@broadcast";
            if (options === null || options === void 0 ? void 0 : options.location) {
                return this.sendLocation(options.type, number, { lat: (_a = options === null || options === void 0 ? void 0 : options.location) === null || _a === void 0 ? void 0 : _a.lat, lon: (_b = options.location) === null || _b === void 0 ? void 0 : _b.lon }, message.text);
            }
            if ((_c = options === null || options === void 0 ? void 0 : options.buttons) === null || _c === void 0 ? void 0 : _c.length) {
                return this.sendButtons(options.type, number, message, options.buttons);
            }
            if (options === null || options === void 0 ? void 0 : options.media) {
                return this.sendMedia(options.type, number, options.media, message.text);
            }
            return this.sendText(options.type, number, message);
        };
        this.sendState = async (message) => {
        };
        this.sendStory = async (media) => {
        };
        this.session = (0, wa_1.getSession)(sessionId);
    }
    async disconnect() {
        return (0, wa_1.deleteSession)(this.sessionId);
    }
    async sendLocation(type, number, { lat, lon }, comment) {
        const exists = await (0, wa_1.jidExists)(this.session, number, type);
        if (!exists) {
            return Error("JID does not exists");
        }
        return await this.session.sendMessage(number, {
            location: { degreesLatitude: lat, degreesLongitude: lon, comment },
        });
    }
}
exports.WebWhatsappProvider = WebWhatsappProvider;
