#include "chatsystem.h"

ChatSystem::ChatSystem()
{

}

void ChatSystem::initialize(CommonClientHandler *commonClientHandler, DataParser *dataParser, QMap<int, ClientHandler*> *clientsMap)
{
    this->commonClientHandler = commonClientHandler;
    this->dataParser = dataParser;
    this->clientsMap = clientsMap;

    clientNotSendedMessage = new QMap<QString,QQueue<ClientMessage>*>;
}

bool ChatSystem::sendTo(ClientMessage message)
{
    QByteArray byteArrayMsg = dataParser->ClientAnswer()->message(message.From,message.To,message.Text);

    foreach(int idSocket, clientsMap->keys())
    {
        ClientHandler *handler = clientsMap->value(idSocket);

        if(handler->getClient()->getId() == message.To &&
           handler->getClient()->getTypeClient() != TypeClientAutorization::TYPE_QT_CLIENT &&
           handler->getClient()->getIsLoggedIn())
        {
            handler->sendXmlAnswer(byteArrayMsg, PacketType::TYPE_XMLANSWER);
            QString str = "Msg From Client [" + message.From + " to " + message.To + "] : " + message.Text;

            return true;
        }
    }

    return false;
}

bool ChatSystem::sendMessage(ClientMessage message)
{
    bool isSended = false;
    isSended = sendTo(message);

    if (!isSended)
    {
        if (clientNotSendedMessage->contains(message.To))
        {
            clientNotSendedMessage->find(message.To).value()->append(message);
        }
        else
        {
            auto stack = new QQueue<ClientMessage>;
            stack->enqueue(message);
            clientNotSendedMessage->insert(message.To, stack);
        }

        qDebug() << "Message stack count: " + QString::number(clientNotSendedMessage->count());
    }

    return true;
}

void ChatSystem::sendOldMessages(QString id)
{
    qDebug() << id;
    if (clientNotSendedMessage->contains(id))
    {
        auto queue = clientNotSendedMessage->find(id).value();
        Logger::instance().log("Send old Messages " + QString::number(queue->length()));

        while (!queue->isEmpty())
        {
            auto message = queue->dequeue();
            sendTo(message);
        }
    }
    else
    {
        qDebug() << "client empty";
    }
}
