#include "SMSGui.h"
#include "ui_SMSGui.h"
#include <QScrollBar>
#include "SMSClient.h"
#include <QKeyEvent>

CSMSGui::CSMSGui(QWidget *parent) :
    QWidget(parent)

{
    setupUi(this);
    mSMSDatabase = 0;
    mSelectedConversation = 0;
    mProgramHandle = 0;
    mCharCounter = 160;
    mMsgCounter = 0;

    mSMSMessageStatsLabel->setText(QString().sprintf("Nombre de caractères du message %d/160\nNombre de messages à envoyer: %d msg",mCharCounter,mMsgCounter+1));

//    connect(mContactsTreeWidget,SIGNAL(itemActivated(QTreeWidgetItem*,int)),this,SLOT(ConversationSelected(QTreeWidgetItem*,int)));
    connect(mContactsTreeWidget,SIGNAL(itemClicked(QTreeWidgetItem*,int)),this,SLOT(ConversationClicked(QTreeWidgetItem*,int)));
    connect(mSMSSendBtn,SIGNAL(clicked(bool)),this,SLOT(SendMsgBtnClicked(bool)));
    connect(mSMSEdit,SIGNAL(textChanged()),this,SLOT(SMSEditZoneContentsChanged()));

    mSMSEdit->installEventFilter(this);
}

CSMSGui::~CSMSGui()
{

}


int CSMSGui::FullConversationsUpdate()
{
    QList<CSMSConversation*> *ConversationsList = mSMSDatabase->GetConversations();

    mContactsTreeWidget->clear();
    mContactsTreeWidget->setColumnCount(3);
    mContactsTreeWidget->setIconSize(QSize(25,25));



    if(ConversationsList->size() > 0)
    {
        for(int i = 0; i < ConversationsList->size(); i++)
        {
            QFont NewMsgFont;
            NewMsgFont.setBold(true);

            QTreeWidgetItem *NewContact = new QTreeWidgetItem(mContactsTreeWidget);
            CSMSConversation *Conversation = ConversationsList->at(i);
            CSMSMessage *LastMsg = Conversation->GetMostRecentMessage();
            NewContact->setIcon(0,QIcon(Conversation->GetConversationContact()->mContactPicture));
            if(LastMsg->mIsRead == false)
            {
                NewContact->setFont(1,NewMsgFont);
                NewContact->setFont(2,NewMsgFont);
            }
            NewContact->setText(1,Conversation->GetConversationContact()->mContactName);
            NewContact->setText(2,Conversation->GetConversationContact()->mContactNumber);
            //        QVariant data = QVariant::fromValue((void*)Conversation);
            NewContact->setData(0,Qt::UserRole,QVariant::fromValue((void*)Conversation));
            mContactsTreeWidget->insertTopLevelItem(0,NewContact);
        }

        mContactsTreeWidget->resizeColumnToContents(0);
        mContactsTreeWidget->resizeColumnToContents(1);
        mContactsTreeWidget->resizeColumnToContents(2);
        mContactsTreeWidget->topLevelItem(0)->setSelected(true);
        ConversationClicked(mContactsTreeWidget->topLevelItem(0),0);
    }


//    mContactsTreeWidget->addTopLevelItem(QTreeWidget());
    return RET_OK;
}

void CSMSGui::ConversationClicked(QTreeWidgetItem *item, int column)
{
    //qDebug("Clicked %d",column);
    mSelectedConversation = (CSMSConversation*) item->data(0,Qt::UserRole).value<void*>();
    QString MessageText;
    MessageText.clear();

    mConversationText->clear();

//    for(int i = 0; i < Conversation->GetMessages()->size(); i++)
    for(int i = mSelectedConversation->GetMessages()->size()-1; i >=0; i--)
    {
        MessageText.append(mSelectedConversation->GetMessages()->at(i)->mDateTime.toString("yyyy/MM/dd hh:mm - "));

        if(mSelectedConversation->GetMessages()->at(i)->mType == SMS_SENT_TYPE)
        {
           MessageText.append("YOU: ");
        }
        else
        {
            MessageText.append(mSelectedConversation->GetConversationContact()->mContactName);
            MessageText.append(": ");
        }
        MessageText.append(mSelectedConversation->GetMessages()->at(i)->mMessageText);
        MessageText.append("\n\r");
    }

    mConversationText->setText(MessageText);

    QFont font;
    font.setBold(false);
    item->setFont(0,font);
    item->setFont(1,font);
    item->setFont(2,font);

    QTextCursor cursor( mConversationText->textCursor() );
    cursor.movePosition( QTextCursor::End );

    QScrollBar *bar = mConversationText->verticalScrollBar();
    if( bar )
    {
      if( !bar->isSliderDown() )
        bar->setValue( bar->maximum() );
    }
    else
        mConversationText->ensureCursorVisible();

    mContactPic->setPixmap(mSelectedConversation->GetConversationContact()->mContactPicture.scaled(mContactPic->size()));
    font.setPointSize(26);
    mContactName->setFont(font);
    mContactName->setText(mSelectedConversation->GetConversationContact()->mContactName);

    mSMSDatabase->SetConversationAsRead(mSelectedConversation);


}

int CSMSGui::UpdateDisplayedConversation(int MessageIndex)
{
    if(MessageIndex != -1)
    {
        QString MessageText;
        MessageText = mConversationText->toPlainText();

        MessageText.append(mSelectedConversation->GetMessages()->at(MessageIndex)->mDateTime.toString("yyyy/MM/dd hh:mm - "));

        if(mSelectedConversation->GetMessages()->at(MessageIndex)->mType == SMS_SENT_TYPE)
        {
           MessageText.append("YOU: ");
        }
        else
        {
            MessageText.append(mSelectedConversation->GetMessages()->at(MessageIndex)->mContact);
            MessageText.append(": ");
        }
        MessageText.append(mSelectedConversation->GetMessages()->at(MessageIndex)->mMessageText);
        MessageText.append("\n\r");

        mConversationText->setText(MessageText);
    }



    QTextCursor cursor( mConversationText->textCursor() );
    cursor.movePosition( QTextCursor::End );

    QScrollBar *bar = mConversationText->verticalScrollBar();
    if( bar )
    {
      if( !bar->isSliderDown() )
        bar->setValue( bar->maximum() );
    }
    else
        mConversationText->ensureCursorVisible();

    return RET_OK;

}

//void CSMSGui::ConversationSelected(QTreeWidgetItem *item, int column)
//{
//   // qDebug("Selected, %d",column);
//}

int CSMSGui::NewMessageNotification(CSMSConversation *Conversation, int MessageIndex)
{
    if(Conversation == 0)
    {
        return NEW_MSG_ERROR_STATUS;
    }
    if(mSelectedConversation == Conversation)   //the new msg comes from the currently displayed contact conversation
    {
        UpdateDisplayedConversation(MessageIndex);
        mSMSDatabase->SetConversationAsRead(mSelectedConversation);
        return NEW_MSG_READ_STATUS;
    }

    //Find conversation...
    for(int i = 0; i < mContactsTreeWidget->topLevelItemCount(); i++)
    {
        void *data = mContactsTreeWidget->topLevelItem(i)->data(0,Qt::UserRole).value<void*>();
        if((CSMSConversation*)data == Conversation)
        {
            //found it!
            QFont font;
            font.setBold(true);
            mContactsTreeWidget->topLevelItem(i)->setFont(0,font);
            mContactsTreeWidget->topLevelItem(i)->setFont(1,font);
            mContactsTreeWidget->topLevelItem(i)->setFont(2,font);
            return NEW_MSG_UNREAD_STATUS;
        }
    }
    return NEW_MSG_ERROR_STATUS;
}

int CSMSGui::SendEditMessage()
{
    if(mSelectedConversation == 0)
    {
        return RET_ERROR;
    }

    QString MsgTxt = mSMSEdit->toPlainText();

    if(MsgTxt.isEmpty())
    {
        return RET_ERROR;
    }

    CSMSMessage Message;
    Message.mContact = mSelectedConversation->mConversationContact.mRAWContactNbr;
    Message.mDID = mSMSDatabase->GetDID();
    Message.mMessageText = MsgTxt;

    mProgramHandle->SendSMSMessage(Message);
    mSMSEdit->clear();

    return RET_OK;
}

void CSMSGui::SendMsgBtnClicked(bool checked)
{
    Q_UNUSED(checked)
    SendEditMessage();
}

bool CSMSGui::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyPress)
    {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if(keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return)
        {
    //        qDebug("Ate key press %d", keyEvent->key());
            SendEditMessage();
            return true;
        }
      //  qDebug("Key press %d", keyEvent->key());

    }

        // standard event processing
        return QObject::eventFilter(obj, event);
}

void CSMSGui::SMSEditZoneContentsChanged()
{
    int CurStringCharCount = mSMSEdit->toPlainText().size();
    if(CurStringCharCount <= 160)
    {
        mCharCounter = 160-CurStringCharCount;
        mMsgCounter = 0;
    }
    else
    {
        mMsgCounter = (int)(CurStringCharCount / 160);
        mCharCounter = 160 - (CurStringCharCount - (mMsgCounter*160));
    }
     mSMSMessageStatsLabel->setText(QString().sprintf("Nombre de caractères du message %d/160\nNombre de messages à envoyer: %d msg",mCharCounter,mMsgCounter+1));

}
