#include <QListWidget>
#include <QKeyEvent>
#include <QAbstractScrollArea>
#include <QMessageBox>
#include <QLabel>
#include "instructor.h"
#include "messangerwidget.h"
#include "ui_messangerwidget.h"


MessangerWidget::MessangerWidget(QWidget *parent) :
    QWidget(parent),    
    oneDialogMessenger(nullptr),
    ui(new Ui::MessangerWidget),
    myTextEdit(nullptr)
{
    ui->setupUi(this);

    ui->btnSend->setObjectName("btnSend");    

    ui->lblUser->setObjectName("MessangerWidgetLblUser");
    ui->lblAvatar->setObjectName("MessangerWidgetLblAvatar");
    ui->lblLoggedIn->setObjectName("MessangerWidgetLblLoggedIn");

    myTextEdit = new MyTextEdit();
    connect(myTextEdit, &MyTextEdit::signal_pressEnter, this, &MessangerWidget::on_btnSend_clicked);

    myTextEdit->setObjectName("editMsg");
    myTextEdit->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
    myTextEdit->setFixedHeight(65);

    ui->horizontalLayout_EditMsg->addWidget(myTextEdit);
}

MessangerWidget::~MessangerWidget()
{
    delete oneDialogMessenger;
    delete ui;
}

void MessangerWidget::initUserRemote(User user)
{
    userRemote = user;

    addTabDialogMessenger(userRemote);
}

void MessangerWidget::reinitMessangerWidget(User user)
{
    if(userRemote.getID() == user.getID())
    {
        userRemote = user;

        //Обновляем заголовок
        updateHeader(userRemote);
    }
}

void MessangerWidget::initUserLocalGUI(User user)
{
    userLocalGUI = user;
}

int MessangerWidget::getIDuserRemote()
{
    return userRemote.getID();
}

void MessangerWidget::showSendedMessage(ClientMessage clientMessage)
{
    if(userLocalGUI.getID() == clientMessage.fromId.toInt())
        oneDialogMessenger->addMsgWidgetLocal(clientMessage.Text, clientMessage.timeStr, userLocalGUI.getName());
}

void MessangerWidget::showReceivedMessage(ClientMessage clientMessage)
{
    if(userRemote.getID() == clientMessage.fromId.toInt())
        oneDialogMessenger->addMsgWidgetRemote(clientMessage.Text, clientMessage.timeStr, userRemote.getName());
}

void MessangerWidget::addTabDialogMessenger(User user)
{
    if(!oneDialogMessenger)
    {//Диалога еще не существует

        oneDialogMessenger = new OneDialogMessenger(userLocalGUI, userRemote, this);

        ui->verticalLayout_ListMsg->addWidget(oneDialogMessenger);

        //Обновляем заголовок
        updateHeader(user);
    }
    else
    {//Диалог уже существует

        //Проверяем наличие диалога именно с этим клиентом
        if(oneDialogMessenger->getUserRemoteId() == user.getID())
        {
            //Обновляем заголовок
            updateHeader(user);
        }
    }
}

void MessangerWidget::updateHeader(User user)
{
    //Обновляем статус залогинивания
    if(user.getLoggedIn())
        ui->lblLoggedIn->setPixmap(QPixmap(QStringLiteral(":/resources/icons/circleGreen.png")));
    else
        ui->lblLoggedIn->setPixmap(QPixmap(QStringLiteral(":/resources/icons/circleGray.png")));


    QString typeUserStr = "";

    if(user.getTypeUserDB() == User::TypeUserDBTrainee)
    {
        ui->lblAvatar->setPixmap(QPixmap(QStringLiteral(":/resources/icons/trainee.png")));

        typeUserStr = tr("Trainee");
    }
    else
    {
        if(static_cast<Instructor*>(&user)->getIsAdmin())
            ui->lblAvatar->setPixmap(QPixmap(QStringLiteral(":/resources/icons/admin.png")));
        else
            ui->lblAvatar->setPixmap(QPixmap(QStringLiteral(":/resources/icons/instructor.png")));

        typeUserStr = tr("Instructor");
    }

    QString fullName = typeUserStr + ": " + user.getName() + " (" + user.getLogin() + ")";
    ui->lblUser->setText(fullName);
}

void MessangerWidget::on_btnSend_clicked()
{
    QString text = myTextEdit->toPlainText();
    QString from = QString::number(userLocalGUI.getID());
    QString to = QString::number(userRemote.getID());

    ClientMessage message = ClientMessage(from, to, text);
    emit signal_sendMessage(message);

    myTextEdit->clear();
}

void MessangerWidget::changeEvent(QEvent *event)
{
    // В случае получения события изменения языка приложения
    if (event->type() == QEvent::LanguageChange)
    {
        ui->retranslateUi(this);    // переведём окно заново
    }
}

void MyTextEdit::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
    {
        if(QApplication::keyboardModifiers().testFlag(Qt::ControlModifier))
        {
            this->insertPlainText("\n");
        }
        else
        {
            emit signal_pressEnter();
            return;
        }
    }
    QTextEdit::keyPressEvent(event);
}
