"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const firebase_1 = require("../config/firebase");
const Admin_1 = require("../models/Admin");
const NotificationAdmin_1 = require("../models/NotificationAdmin");
const NotificationUser_1 = require("../models/NotificationUser");
const User_1 = require("../models/User");
const twilio = require("twilio");
require("dotenv").config();
class Helper {
    constructor() {
        this.adminId = "672371c01beafa2fac8d313b";
    }
    generatePassword(length, options) {
        return __awaiter(this, void 0, void 0, function* () {
            const optionsChars = {
                digits: "1234567890",
                lowercase: "abcdefghijklmnopqrstuvwxyz",
                uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                symbols: "@$!%&",
            };
            const chars = [];
            for (let key in options) {
                if (options.hasOwnProperty(key) &&
                    options[key] &&
                    optionsChars.hasOwnProperty(key)) {
                    chars.push(optionsChars[key]);
                }
            }
            if (!chars.length)
                return "";
            let password = "";
            for (let j = 0; j < chars.length; j++) {
                password += chars[j].charAt(Math.floor(Math.random() * chars[j].length));
            }
            if (length > chars.length) {
                length = length - chars.length;
                for (let i = 0; i < length; i++) {
                    const index = Math.floor(Math.random() * chars.length);
                    password += chars[index].charAt(Math.floor(Math.random() * chars[index].length));
                }
            }
            return password;
        });
    }
    generateRandomString(length, options) {
        return __awaiter(this, void 0, void 0, function* () {
            const optionsChars = {
                digits: "1234567890",
                lowercase: "abcdefghijklmnopqrstuvwxyz",
                uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
            };
            const chars = [];
            for (let key in options) {
                if (options.hasOwnProperty(key) &&
                    options[key] &&
                    optionsChars.hasOwnProperty(key)) {
                    chars.push(optionsChars[key]);
                }
            }
            if (!chars.length)
                return "";
            let randomString = "";
            for (let j = 0; j < chars.length; j++) {
                randomString += chars[j].charAt(Math.floor(Math.random() * chars[j].length));
            }
            if (length > chars.length) {
                length = length - chars.length;
                for (let i = 0; i < length; i++) {
                    const index = Math.floor(Math.random() * chars.length);
                    randomString += chars[index].charAt(Math.floor(Math.random() * chars[index].length));
                }
            }
            return randomString;
        });
    }
    sendNotification(from_id, to_id, title, description, data = {
        type: "GENERAL",
    }) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                // Get To User ID Token.
                const receiver = yield User_1.default.findById(to_id);
                yield new NotificationUser_1.default({
                    from_id: from_id,
                    to_id: to_id,
                    title: title,
                    description: description,
                    data,
                }).save();
                // If user notification toggle is true then only send notification to receiver user.
                if (receiver && receiver.notification == true) {
                    if (receiver && receiver.device_token) {
                        const message = {
                            notification: {
                                title: title,
                                body: description,
                            },
                            data: data,
                            token: receiver.device_token,
                        };
                        console.log(message, JSON.stringify(message));
                        firebase_1.default
                            .messaging()
                            .send(message)
                            .then((response) => {
                            console.log(`Notification sent successfully : ${data === null || data === void 0 ? void 0 : data.type}`, response);
                        })
                            .catch((err) => console.log(err, "Firebase ERROR"));
                    }
                }
            }
            catch (error) {
                console.log("Error while sending notification : ", error);
                // return error;
            }
        });
    }
    sendNotificationToAdmin(from_id, to_id, title, description) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                // Get To User ID Token.
                const receiver = yield Admin_1.default.findById(to_id);
                // If user notification toggle is true then only send notification to receiver user.
                if (receiver && receiver.notification == true) {
                    yield new NotificationAdmin_1.default({
                        from_id: from_id,
                        to_id: to_id,
                        title: title,
                        description: description,
                    }).save();
                    if (receiver && receiver.device_token) {
                        const message = {
                            notification: {
                                title: title,
                                body: description,
                            },
                            token: receiver.device_token,
                        };
                        firebase_1.default
                            .messaging()
                            .send(message)
                            .then((response) => {
                            console.log("Notification sent successfully : ", response);
                        })
                            .catch((err) => console.log(err, "Firebase ERROR"));
                    }
                }
            }
            catch (error) {
                console.log("Error while sending notification : ", error);
                // return error;
            }
        });
    }
    sendSMS(to, body) {
        return __awaiter(this, void 0, void 0, function* () {
            const accountSid = process.env.TWILIO_ACCOUNT_SID;
            const authToken = process.env.TWILIO_AUTH_TOKEN;
            const twilioNumber = process.env.TWILIO_NUMBER
                ? process.env.TWILIO_NUMBER
                : "+12512734667";
            const client = new twilio(accountSid, authToken);
            try {
                const message = yield client.messages.create({
                    body: body,
                    to: "+" + to,
                    from: twilioNumber,
                });
                console.log("SMS has been sent successfully", message);
                return true;
            }
            catch (error) {
                console.error("Somthing went wrong, Error is", error);
                return false;
            }
        });
    }
    generateAssetUrl(req, assetPath) {
        const protocol = req.protocol; // 'http' or 'https'
        const host = req.get("host"); // Gets the host (domain + port if not 80/443)
        return `${protocol}://${host}/public/${assetPath}`;
    }
    generateListWithAssetUrl(req, list) {
        const protocol = req.protocol;
        const host = req.get("host");
        list.docs.forEach((doc) => {
            doc.image = doc.image ? `${protocol}://${host}/public${doc.image}` : "";
        });
        return list;
    }
}
exports.default = new Helper();
