/*
 * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * This component and the accompanying materials are made available
 * under the terms of "Eclipse Public License v1.0"
 * which accompanies this distribution, and is available
 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
 *
 * Initial Contributors:
 * Nokia Corporation - initial contribution.
 *
 * Contributors:
 *
 * Description:
 *
 */

#include "msgunieditorbodyeditor.h"

// SYSTEM INCLUDES
#include <HbStyle>
#include <HbPushButton>
#include <HbTextItem>
#include <HbFrameDrawer>
#include <HbFrameItem>
#include <csmsaccount.h>
#include <smutset.h>
#include <hbmessagebox.h>
#include <hbcolorscheme.h>
#include <QColor>

#include "unieditorpluginloader.h"
#include "unieditorplugininterface.h"
#include "UniSendingSettings.h"
#include "UniEditorGenUtils.h"
#include "msgunieditormonitor.h"
#include "debugtraces.h"

// LOCAL CONSTANTS

const QString SEND_ICON("qtg_mono_send");
const QString BACKGROUND("qtg_fr_input_v_bg");
const QString BACKGROUND_FRAME("qtg_fr_messaging_char_count");
const QString CHAR_COUNTER_COLOR("qtc_messaging_char_count");

const QString SEND_BUTTON_NORMAL("qtg_fr_btn_green_normal");
const QString SEND_BUTTON_PRESSED("qtg_fr_btn_green_pressed");
const QString SEND_BUTTON_DISABLED("qtg_fr_btn_disabled");

const QString SEND_BUTTON_NORMAL_COLOR("qtc_callhandling_answer_normal");
const QString SEND_BUTTON_PRESSED_COLOR("qtc_callhandling_answer_pressed");
const QString SEND_BUTTON_DISABLED_COLOR("qtc_button_disabled");

#define LOC_SMS_CHAR_LIMIT_REACHED hbTrId("txt_messaging_dialog_sms_character_count_exceeded")
#define LOC_HINT_TEXT hbTrId("txt_messaging_formlabel_enter_message_here")
#define LOC_UNABLE_TO_ADD_CONTENT hbTrId("txt_messaging_dpopinfo_unable_to_add_more_content")

  
const TInt KShowCounterLimit = 10;


//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::MsgUnifiedEditorBodyEditor
// @see header
//---------------------------------------------------------------
MsgUnifiedEditorBodyEditor::MsgUnifiedEditorBodyEditor(QGraphicsItem *parent) :
MsgUnifiedEditorBaseWidget(parent),
mMsgEditor(NULL),
mSendButton(NULL),
mPluginLoader(NULL)
{
    this->setObjectName("bodyText");
    
    setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
    
    //setting background.
    HbFrameItem* backGround = new HbFrameItem(this);
    backGround->frameDrawer().setFrameGraphicsName(BACKGROUND);
    backGround->frameDrawer().setFrameType(HbFrameDrawer::ThreePiecesVertical);
    backGround->frameDrawer().setFillWholeRect(true);
    //fixing to 2 pixel to avoid extra line on top of frame.
    backGround->frameDrawer().setBorderWidth(2);
    this->setBackgroundItem(backGround); 

    // Initialize the widget.
    init();
    
    setEncodingSettingsL();
}

//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::init
// @see header
//---------------------------------------------------------------
void MsgUnifiedEditorBodyEditor::init()
{
    // Create mandatory element of mesh layout.
    mMsgEditor = new MsgEditor(this);
    HbStyle::setItemName(mMsgEditor, "msgEditor");

	mSendButton = new HbPushButton(this); 
    HbStyle::setItemName(mSendButton, "sendButton"); 
    mSendButton->setEnabled(false); 
    
    HbFrameItem* backGround = new HbFrameItem(this); 
    backGround->frameDrawer().setFrameType(HbFrameDrawer::NinePieces); 
    mSendButton->setBackgroundItem(backGround); 
    updateButtonBackgroundAndColor(SEND_BUTTON_DISABLED,SEND_BUTTON_DISABLED_COLOR); 
    mSendButton->setIcon(HbIcon(SEND_ICON));
    
    mCharCounter = new HbTextItem(this);
    HbStyle::setItemName(mCharCounter, "charCounter");
    mCharCounter->setZValue(1.5);
    
    QColor color = HbColorScheme::color(CHAR_COUNTER_COLOR);
    mCharCounter->setTextColor(color);
    
    mBackgroundItem = new HbFrameItem(this);
    HbStyle::setItemName(mBackgroundItem, "charCounterFrame");

    mBackgroundItem->frameDrawer().setFrameType(HbFrameDrawer::ThreePiecesHorizontal);
    mBackgroundItem->frameDrawer().setFillWholeRect(true);
    
    mBackgroundItem->frameDrawer().setFrameGraphicsName(BACKGROUND_FRAME);    
    
    //Create editor utils object
    mEditorUtils = q_check_ptr(new UniEditorGenUtils());

    connect(mSendButton, SIGNAL(clicked()),this, SIGNAL(sendMessage()));
    connect(mSendButton, SIGNAL(pressed()),this, SLOT(onPressed()));
    connect(mSendButton, SIGNAL(released()),this, SLOT(onReleased()));
    connect(mMsgEditor,  SIGNAL(contentsChanged()),this,SLOT(onContentsChanged()));
    
}

//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::~MsgUnifiedEditorBodyEditor
// @see header
//---------------------------------------------------------------
MsgUnifiedEditorBodyEditor::~MsgUnifiedEditorBodyEditor()
{
    delete mEditorUtils;
}

//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::content
// @see header
//---------------------------------------------------------------
QString MsgUnifiedEditorBodyEditor::content() const
{
    return mMsgEditor->toPlainText();
}

//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::setContent
// @see header
//---------------------------------------------------------------
void MsgUnifiedEditorBodyEditor::setContent(const QString &text)
{
    mMsgEditor->setPlainText(text);
}

//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::enableSendButton
// @see header
//---------------------------------------------------------------
void  MsgUnifiedEditorBodyEditor::enableSendButton(bool enable)
{
    if(enable)
    {
        if(!mSendButton->isEnabled())
        {
            mSendButton->setFocusProxy(mMsgEditor);
            mSendButton->setEnabled(true);
            updateButtonBackgroundAndColor(SEND_BUTTON_NORMAL,SEND_BUTTON_NORMAL_COLOR);
        }
    }
    else
    {
        if(mSendButton->isEnabled())
        {
            mSendButton->setFocusProxy(0);
            mSendButton->setEnabled(false);
            updateButtonBackgroundAndColor(SEND_BUTTON_DISABLED,SEND_BUTTON_DISABLED_COLOR);
        }
    }
}

//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::onContentsChanged
// @see header
//---------------------------------------------------------------
void MsgUnifiedEditorBodyEditor::onContentsChanged()
{
    QString text = this->content();
   
    mPluginInterface->setEncodingSettings(EFalse, ESmsEncodingNone,mCharSupportType);

    TInt numOfRemainingChars;
    TInt numOfPDUs;
    TBool unicodeMode;
    TSmsEncoding alternativeEncodingType;
    mPluginInterface->getNumPDUs(text, numOfRemainingChars, numOfPDUs,
                                 unicodeMode, alternativeEncodingType);

    // emit signal to indicate change in content
    int contentSize = mEditorUtils->UTF8Size(text);    
    QVariantList dataList;
    dataList << contentSize << unicodeMode;
    emit contentsChanged(dataList);    

    if(MsgUnifiedEditorMonitor::messageType() == ConvergedMessage::Sms)
    {
        //Set char counter value
        QString display = QString("%1(%2)").arg(numOfRemainingChars).arg(
            numOfPDUs);
        mCharCounter->setText(display);

        if (numOfPDUs > 1 || numOfRemainingChars <= KShowCounterLimit)
        {
            mCharCounter->setVisible(true);
            mBackgroundItem->setVisible(true);
        }
        else
        {
            mCharCounter->setVisible(false);
            mBackgroundItem->setVisible(false);
        }
    }
}

//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::updateButtonBackgroundAndColor
// @see header
//---------------------------------------------------------------
void MsgUnifiedEditorBodyEditor::updateButtonBackgroundAndColor(const QString& bg,const QString& iconColor) 
{ 
    HbFrameItem* drawer = static_cast<HbFrameItem*>(mSendButton->backgroundItem()); 
    if(drawer) 
    { 
        drawer->frameDrawer().setFrameGraphicsName(bg);   
    } 
    QColor color = HbColorScheme::color(iconColor);

    if(color.isValid())
    {
        mSendButton->icon().setColor(color);
    }	    
} 
    
//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::onPressed
// @see header
//---------------------------------------------------------------
void MsgUnifiedEditorBodyEditor::onPressed()
{
    updateButtonBackgroundAndColor(SEND_BUTTON_PRESSED,SEND_BUTTON_PRESSED_COLOR);
}

//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::onReleased
// @see header
//---------------------------------------------------------------
void MsgUnifiedEditorBodyEditor::onReleased()
{
    updateButtonBackgroundAndColor(SEND_BUTTON_NORMAL,SEND_BUTTON_NORMAL_COLOR);
}
	
//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::setEncodingSettingsL
// @see header
//---------------------------------------------------------------
void MsgUnifiedEditorBodyEditor::setEncodingSettingsL()
{ 
    mPluginLoader = new UniEditorPluginLoader(this);

    mPluginInterface =
        mPluginLoader->getUniEditorPlugin(ConvergedMessage::Sms);    

    QT_TRAP_THROWING( CSmsSettings* settings = CSmsSettings::NewLC();
    CSmsAccount* account = CSmsAccount::NewLC();
    account->LoadSettingsL( *settings );

    if( settings->CharacterSet() == TSmsDataCodingScheme::ESmsAlphabetUCS2)
    {
        mCharSupportType = TUniSendingSettings::EUniCharSupportFull;
    }
    else
    {
        mCharSupportType = TUniSendingSettings::EUniCharSupportReduced;
    }

    CleanupStack::PopAndDestroy( account );
    CleanupStack::PopAndDestroy( settings ));


    mCharCounter->setVisible(false);
    mBackgroundItem->setVisible(false);
}

//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::packMessage
// @see header
//---------------------------------------------------------------
void MsgUnifiedEditorBodyEditor::packMessage(ConvergedMessage &msg)
{
    msg.setBodyText(mMsgEditor->toPlainText());
}

//---------------------------------------------------------------
// MsgUnifiedEditorBodyEditor::populateContent
// @see header
//---------------------------------------------------------------
void MsgUnifiedEditorBodyEditor::populateContent(const ConvergedMessage& msg)
{
    QString bodyTxt = msg.bodyText();
    mMsgEditor->setPlainText(msg.bodyText());
}

//---------------------------------------------------------------
// MsgEditor::MsgEditor
// @see header
//---------------------------------------------------------------
MsgEditor::MsgEditor(QGraphicsItem *parent) :
HbTextEdit(parent)
{
    this->setFontSpec(HbFontSpec(HbFontSpec::Secondary));
    this->setPlaceholderText(LOC_HINT_TEXT);
    this->setSmileysEnabled(true);
}

//---------------------------------------------------------------
// MsgEditor::inputMethodEvent
// @see header
//---------------------------------------------------------------
void MsgEditor::inputMethodEvent(QInputMethodEvent *event)
{
    bool showNote = false;
    
    if( MsgUnifiedEditorMonitor::messageType() == ConvergedMessage::Mms && 
        !event->commitString().isEmpty())
    {
        QString str = event->commitString();
        int comitStrSize = str.toUtf8().size();
        
        if(MsgUnifiedEditorMonitor::messageSize()+ comitStrSize > MsgUnifiedEditorMonitor::maxMmsSize())
        {
            showNote = true;  
            // reject any text input if mms size limit is reached
            event->setCommitString(QString());             
        }
    }
    
    HbTextEdit::inputMethodEvent(event); 

    if(showNote)
    {
        HbMessageBox* mb = new HbMessageBox(LOC_UNABLE_TO_ADD_CONTENT,HbMessageBox::MessageTypeInformation);
        mb->setStandardButtons(HbMessageBox::Ok);
        mb->setAttribute(Qt::WA_DeleteOnClose);
        mb->setFocusPolicy(Qt::NoFocus);
        mb->show();
    }
}

// EOF
