#include "msgwidget.h"
#include "ui_msgwidget.h"

MsgWidget::MsgWidget(QString avatar, AligneAvatar aligneAvatar, int width, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MsgWidget),
    widthEdit(100)
{
    ui->setupUi(this);

    setAvatar(avatar);

    if(aligneAvatar == AligneAvatar::Left)
        setAligneAvatarLeft();
    else
        setAligneAvatarRight();

    setWidth(width);
}

MsgWidget::~MsgWidget()
{
    delete ui;
}

void MsgWidget::setAligneAvatarLeft()
{
    ui->horizontalLayout->removeWidget(ui->textEdit);
    ui->horizontalLayout->removeItem(ui->verticalLayout);
    ui->horizontalLayout->removeItem(ui->horizontalLayout_2);

    ui->horizontalLayout->addLayout(ui->verticalLayout);
    ui->horizontalLayout->addWidget(ui->textEdit);
    ui->horizontalLayout->addLayout(ui->horizontalLayout_2);

    ui->textEdit->setObjectName("MsgWidgetLocal");
}

void MsgWidget::setAligneAvatarRight()
{
    ui->horizontalLayout->removeWidget(ui->textEdit);
    ui->horizontalLayout->removeItem(ui->verticalLayout);
    ui->horizontalLayout->removeItem(ui->horizontalLayout_2);

    ui->horizontalLayout->addLayout(ui->horizontalLayout_2);
    ui->horizontalLayout->addWidget(ui->textEdit);
    ui->horizontalLayout->addLayout(ui->verticalLayout);

    ui->textEdit->setObjectName("MsgWidgetRemote");
}


void MsgWidget::setAvatar(QString avatar)
{
    QPixmap pix(avatar);
    ui->label->setPixmap( pix.scaled(32,32) );
}

void MsgWidget::setWidth(int width)
{
    this->setFixedWidth(width);
    widthEdit = width - 200;
}

void MsgWidget::setText(QString text)
{
    ui->textEdit->setText(text);
}

void MsgWidget::on_textEdit_textChanged()
{
    QString text = ui->textEdit->toPlainText();
    QFontMetrics metricsFont(ui->textEdit->font()); //метрики шрифта

    //геометрические параметры текста (высота/ширина в пикселях). В одну строку
    QRect textRect = metricsFont.boundingRect(QRect(0, 0, 0, 0), 0, text);

    int X = 10; // отступы

    if(textRect.width() > widthEdit)
    {//Не помещается в одну строку
        textRect = metricsFont.boundingRect(QRect(0, 0, widthEdit, 10), Qt::TextWordWrap, text);
        ui->textEdit->setFixedHeight(textRect.height() + X);
        this->setFixedHeight(textRect.height() + X + 20);
    }
    else
    {//В одну строку
        ui->textEdit->setFixedWidth(textRect.width() + X);
        ui->textEdit->setFixedHeight(textRect.height() + X);
        this->setFixedHeight(textRect.height() + X + 20);
    }
}
