"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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.remove = exports.update = exports.show = exports.customization = exports.store = exports.listQueues = exports.index = void 0;
const socket_1 = require("../libs/socket");
const CreateQueueService_1 = __importDefault(require("../services/QueueService/CreateQueueService"));
const DeleteQueueService_1 = __importDefault(require("../services/QueueService/DeleteQueueService"));
const ListQueuesService_1 = __importDefault(require("../services/QueueService/ListQueuesService"));
const ShowQueueService_1 = __importDefault(require("../services/QueueService/ShowQueueService"));
const UpdateQueueService_1 = __importDefault(require("../services/QueueService/UpdateQueueService"));
const Queue_1 = __importDefault(require("../models/Queue"));
const AppError_1 = __importDefault(require("../errors/AppError"));
const RedisClient_1 = require("../helpers/RedisClient");
const sequelize_1 = require("sequelize");
const Whatsapp_1 = __importDefault(require("../models/Whatsapp"));
const QuickAnswerQueue_1 = __importDefault(require("../models/QuickAnswerQueue"));
const ContactQueues_1 = __importDefault(require("../models/ContactQueues"));
const index = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const queues = yield ListQueuesService_1.default();
    return res.status(200).json(queues);
});
exports.index = index;
const listQueues = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    const whatsapps = yield Whatsapp_1.default.findAll({
        where: {
            name: { [sequelize_1.Op.ne]: "botqueue" },
            number: { [sequelize_1.Op.ne]: "" },
            phoneNumberId: false
        },
        attributes: ["number"],
        include: [
            {
                model: Queue_1.default,
                as: "queues",
                attributes: ["id", "name"]
            }
        ]
    });
    const whats = (_a = whatsapps === null || whatsapps === void 0 ? void 0 : whatsapps.filter((w) => { var _a; return ((_a = w === null || w === void 0 ? void 0 : w.queues) === null || _a === void 0 ? void 0 : _a.length) > 0; })) === null || _a === void 0 ? void 0 : _a.map((w) => {
        const { number, queues } = w;
        return {
            number,
            queues: queues === null || queues === void 0 ? void 0 : queues.map((q) => {
                const { id, name } = q;
                return { id, name };
            })
        };
    });
    let _queues = [];
    for (const w of whats) {
        const { queues } = w;
        for (const q of queues) {
            const { id: queueId, name } = q;
            const auxQueue = _queues.findIndex((q) => q.queueId == queueId);
            if (auxQueue == -1) {
                _queues.push({ queueId, name });
            }
        }
    }
    return res.status(200).json(_queues);
});
exports.listQueues = listQueues;
const store = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { name, color, greetingMessage, farewellMessage, cc } = req.body;
    const queue = yield CreateQueueService_1.default({
        name,
        color,
        greetingMessage,
        cc,
        farewellMessage
    });
    const io = socket_1.getIO();
    io.emit("queue", {
        action: "update",
        queue
    });
    return res.status(200).json(queue);
});
exports.store = store;
const customization = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { ura } = req.body;
    if (!ura)
        throw new AppError_1.default("BAD REQUEST", 400);
    let new_queues;
    if (ura.length > 0) {
        new_queues = ura
            .filter((u) => u.idmaster === ura[1].id && (u === null || u === void 0 ? void 0 : u.queueName) && (u === null || u === void 0 ? void 0 : u.color) && (u === null || u === void 0 ? void 0 : u.greetingMessage))
            .map((u) => {
            var _a;
            const { queueName, color, greetingMessage } = u;
            return {
                queueName: (_a = queueName === null || queueName === void 0 ? void 0 : queueName.trim()) === null || _a === void 0 ? void 0 : _a.replace(/\s+/g, " "),
                color,
                greetingMessage
            };
        });
        if (new_queues && new_queues.length > 0) {
            const db_queues = yield Queue_1.default.findAll();
            // for (const i in new_queues) {
            //   let { queueName: name, color, greetingMessage } = new_queues[i];
            //   name = name?.trim()?.replace(/\s+/g, " ");
            //   const update = db_queues.find(
            //     (q: any) => q.name?.trim()?.replace(/\s+/g, " ") == name
            //   );
            //   if (update) {
            //     const { id } = update;
            //     // UPDATE
            //     // const queue = await UpdateQueueService(id, {
            //     //   name,
            //     //   color,
            //     //   greetingMessage
            //     // });
            //     // const io = getIO();
            //     // io.emit("queue", {
            //     //   action: "update",
            //     //   queue
            //     // });
            //   } else {
            //     // CREATE
            //     // const queue = await CreateQueueService({
            //     //   name,
            //     //   color,
            //     //   greetingMessage
            //     // });
            //     // const io = getIO();
            //     // io.emit("queue", {
            //     //   action: "update",
            //     //   queue
            //     // });
            //   }
            // }
            let remove_queues = db_queues.filter((q) => {
                var _a, _b;
                return !new_queues
                    .map((nq) => nq.queueName)
                    .includes((_b = (_a = q.name) === null || _a === void 0 ? void 0 : _a.trim()) === null || _b === void 0 ? void 0 : _b.replace(/\s+/g, " "));
            });
            for (const i in remove_queues) {
                const { id, name } = remove_queues[i];
                // await DeleteQueueService(id);
                // const io = getIO();
                // io.emit("queue", {
                //   action: "delete",
                //   queueId: +id
                // });
            }
            // await set("ura", ura);
        }
    }
    yield RedisClient_1.set("ura", ura);
    const _ura = yield RedisClient_1.get({ key: "ura", parse: true });
    console.log("_URA: ", _ura);
    return res.status(200).json({ new_queues });
});
exports.customization = customization;
const show = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { queueId } = req.params;
    const queue = yield ShowQueueService_1.default(queueId);
    return res.status(200).json(queue);
});
exports.show = show;
const update = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { queueId } = req.params;
    const queue = yield UpdateQueueService_1.default(queueId, req.body);
    const io = socket_1.getIO();
    io.emit("queue", {
        action: "update",
        queue
    });
    return res.status(201).json(queue);
});
exports.update = update;
const remove = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { queueId } = req.params;
    yield DeleteQueueService_1.default(queueId);
    yield QuickAnswerQueue_1.default.destroy({ where: { queueId } });
    yield ContactQueues_1.default.destroy({ where: { queueId } });
    yield RedisClient_1.del(`queue:${queueId}`);
    const io = socket_1.getIO();
    io.emit("queue", {
        action: "delete",
        queueId: +queueId
    });
    return res.status(200).send();
});
exports.remove = remove;
