// Method to find a named field within the Cache Control header
//
// In:
//  aSource		- the descriptor containing the date value
//	aFrom		- The position in the descriptor to start from
//
// Out:
//  aTime - a structure containing the time (and date) found in the descriptor
//
// NOTE THIS METHOD WAS EXPORTED FOR TESTING OF THE CACHE. IT SHOULDN'T BE
// NOW, BUT CAN'T BE CHANGED SINCE IT WOULD AFFECT BC.
void CHTTPResponse::ExtractFieldDateValue(const TPtrC8& aSource,
										  TInt aFrom,
										  TTime& aTime) const
	{
	__LOG_ENTER(_L("CHTTPResponse::ExtractFieldDateValue"));
	// Get num bytes encoding the date - 
	// we are positioned at that location in the source descriptor
    TInt time = 0;
	TPtrC8 integerSource = aSource.Mid(aFrom);
	ExtractMultiOctetInteger(time, integerSource);
	// The WSP Date encoding is the number of seconds since the start of the
	// UNIX epoch (00:00:00.000, 01-Jan-1970), as a long integer
	TDateTime unixEpocDT(1970, EJanuary, 0, 0, 0, 0, 0);
	TTime unixEpoch(unixEpocDT);
    TTimeIntervalSeconds timeSeconds(time);
    aTime = unixEpoch + timeSeconds;
	__LOG_RETURN;
	}
//---------------------------------------------------------------
// TestUniDataModelPlugin::createMMS
//---------------------------------------------------------------
void TestUniDataModelMMSPlugin::createMMS(TMsvId pId, TBool subjectField)
    {
    TMsvEntry indexEntry;
    indexEntry.iType = KUidMsvMessageEntry;
    indexEntry.iMtm = KUidMsgTypeMultimedia;
    indexEntry.iServiceId = iServiceId;
    indexEntry.iDate.HomeTime();
    
    // Convert TTime to QDateTime , this will be used for comparing the time of mesage 
    // when fetched from datamodel
    TTime unixEpoch(KUnixEpoch);
    TTimeIntervalSeconds seconds;
    TTime timeStamp = indexEntry.iDate;
    timeStamp.SecondsFrom(unixEpoch, seconds);
    retTimeStamp.setTime_t(seconds.Int());

    TMsvId parentId = pId;
    CMsvEntry* entry = CMsvEntry::NewL(*iMSession,parentId,TMsvSelectionOrdering());
    CleanupStack::PushL(entry);

    entry->SetEntryL(parentId);
    entry->CreateL(indexEntry);
    entry->SetEntryL(indexEntry.Id());
    iMmsClientMtm->SwitchCurrentEntryL(entry->EntryId());

    CMsvStore* store = iMmsClientMtm->Entry().EditStoreL();
    CleanupStack::PushL(store);
      
    //MMS Message ID Saved
    iMessageId = indexEntry.Id();
    
    //Adding Subject
    if(subjectField)
        {
        QString subject(TEST_MSG_SUBJECT);
        HBufC* subj = XQConversions::qStringToS60Desc(subject);
        iMmsClientMtm->SetSubjectL(*subj);
        }

    //Adding Sender
    QString sender(TEST_MSG_FROM1);
    HBufC* addr = XQConversions::qStringToS60Desc(sender);
    
    if (addr)
        {
        CleanupStack::PushL(addr);
        TBuf<32> name;
        name.Copy(addr->Left(32));
        indexEntry.iDetails.Set(name);
        
        iMmsClientMtm->SetSenderL(*addr);
        
        CleanupStack::PopAndDestroy(addr);
        }
    
    //Adding Recipient
    QString recipient(TEST_MSG_RECIEPIENT1);
    HBufC* addr2 = XQConversions::qStringToS60Desc(recipient);
    if (addr2)
        {
        CleanupStack::PushL(addr2);
        iMmsClientMtm->AddAddresseeL(EMsvRecipientTo,*addr2);
        CleanupStack::PopAndDestroy(addr2);
        }
    
    //Adding cCRecipient
    QString recipient2(TEST_MSG_RECIEPIENT2);
    HBufC* addr3 = XQConversions::qStringToS60Desc(recipient2);
    if (addr3)
        {
        CleanupStack::PushL(addr3);
        iMmsClientMtm->AddAddresseeL(EMsvRecipientCc,*addr3);
        CleanupStack::PopAndDestroy(addr3);
        }
      
    //Adding bCCRecipient
    QString recipient3(TEST_MSG_RECIEPIENT3);
	HBufC* addr4 = XQConversions::qStringToS60Desc(recipient3);
	if (addr4)
		{
		CleanupStack::PushL(addr4);
		iMmsClientMtm->AddAddresseeL(EMsvRecipientBcc,*addr4);
		CleanupStack::PopAndDestroy(addr4);
		}
	
    //Create Text Attachment
    TMsvAttachmentId attaId = 0;
    TFileName attachmentFile( _L("story.txt") );
    TBufC<12> story = _L( "Hello world!" );
    
    iMmsClientMtm->CreateTextAttachmentL(*store, attaId, story, attachmentFile, ETrue );
    qDebug() << "Text Attachment id" << attaId;
    
    //Image Attachment added to the message entry
    RFile attaFile;
	// Set filename of attachment
	TFileName name( KPictureFileName );
   
	CMsvMimeHeaders* mimeHeaders = CMsvMimeHeaders::NewL();
	CleanupStack::PushL( mimeHeaders );
   
	// Set values to mime headers
	mimeHeaders->SetContentTypeL( _L8( "image") );
	mimeHeaders->SetContentSubTypeL( _L8( "jpeg" ) );
   
	_LIT8(KMimeType, "image/jpeg");
	TBufC8<10> mimeType(KMimeType);
	// CreateAttachment2L will set the content type to attachment Info
   
	// Open the attachment file for reading
	attaFile.Open( iFs, name, EFileShareReadersOnly | EFileRead );
	CleanupClosePushL(attaFile);
   
	CMsvAttachment* attaInfo = CMsvAttachment::NewL(CMsvAttachment::EMsvFile);
	// attaInfo ownerhip will be transferred to Attachment Manager.
	// It must not be pushed onto the cleanupStack before calling 
	// CreateAttachment2L.
   
	iMmsClientMtm->CreateAttachment2L(*store, attaFile,mimeType,*mimeHeaders,attaInfo,attaId);
	qDebug() << "Image Attachment id" << attaId;
	
	// Now Attachment Manager owns the attaInfo
	CleanupStack::Pop(); // attaFile.Close()
	CleanupStack::PopAndDestroy(); // mimeHeaders
        
    store->CommitL();
    
    CleanupStack::PopAndDestroy(store); // store
    
    iMmsClientMtm->SaveMessageL();
    
    //Saving the message size for future checking
    msgSize = iMmsClientMtm->MessageSize();
    
    CleanupStack::Pop(entry); // entry
    }
//---------------------------------------------------------------
// ConversationsModel::populateItem
// @see header
//---------------------------------------------------------------
void ConversationsModel::populateItem(QStandardItem& item, const CCsConversationEntry& entry)
{
    QCRITICAL_WRITE("ConversationsModel::populateItem start.");

    int msgId = entry.EntryId();
    // id
    item.setData(msgId, ConvergedMsgId);

    // description
    HBufC* description = entry.Description();
    QString subject("");
    if (description && description->Length()) {
        subject = (XQConversions::s60DescToQString(*description));     
    }

    // time stamp
    TTime unixEpoch(KUnixEpoch);
    TTimeIntervalSeconds seconds;
    TTime timeStamp(entry.TimeStamp());
    timeStamp.SecondsFrom(unixEpoch, seconds);
    item.setData(seconds.Int(), TimeStamp);

    //contact details
    HBufC* contact = entry.Contact();
    if (contact && contact->Length()) {
        item.setData(XQConversions::s60DescToQString(*contact), ConversationAddress);
    }

    // message type.
    int msgType = ConversationsEngineUtility::messageType(entry.GetType());
    item.setData(msgType, MessageType);

    //message sub-type
    item.setData(ConversationsEngineUtility::messageSubType(entry.GetType()), MessageSubType);

    // unread status
    if (entry.IsAttributeSet(ECsAttributeUnread)) {
        item.setData(true, UnReadStatus);
    }
    else {
        item.setData(false, UnReadStatus);
    }

    //sending state
    item.setData(entry.GetSendState(), SendingState);
    // direction
    item.setData(entry.ConversationDir(), Direction);

    //location
    if (entry.ConversationDir() == ECsDirectionIncoming) {
        item.setData(ConvergedMessage::Inbox, MessageLocation);
    }
    else if (entry.IsAttributeSet(ECsAttributeDraft)) {
        item.setData(ConvergedMessage::Draft, MessageLocation);
    }
    else if (entry.IsAttributeSet(ECsAttributeSent)) {
        item.setData(ConvergedMessage::Sent, MessageLocation);
    }
    else {
        item.setData(ConvergedMessage::Outbox, MessageLocation);
    }

    //message specific handling
    if (msgType == ConvergedMessage::Mms) {
        QCRITICAL_WRITE("ConversationsModel::populateItem  MMS start.")
        handleMMS(item, entry);
        QCRITICAL_WRITE("ConversationsModel::populateItem MMS end.")
    }
TMsvId TestUniDataModelVCalPlugin::CreateBIOEntryL(TDesC& aText,
                                                   TBIOMessageType aMessageType)
{
		// Ensure that we have a valid service ID to work with:
		TMsvId iBioServiceId;

		iBioServiceId = SetBIOServiceIdL();

		HBufC* localBuffer = aText.AllocL();
		CleanupStack::PushL(localBuffer);

		TPtr messDes = localBuffer->Des();

		if (aMessageType != EBiovCardMessage && aMessageType
            != EBiovCalenderMessage)
			{
				// convert \r\n to \n since this is what is expected from SMS when not vCard data
				for (TInt i = 0; i < messDes.Length(); i++)
					{
						if (messDes[i] == (TText) '\r' && i < messDes.Length() - 1
								&& messDes[i + 1] == (TText) '\n')
							messDes.Delete(i, 1);
					}
			}

		//  Create and fill a CRichText object for the jobbie:
		CParaFormatLayer* paraFormatLayer = CParaFormatLayer::NewL();
		CleanupStack::PushL(paraFormatLayer);
		CCharFormatLayer* charFormatLayer = CCharFormatLayer::NewL();
		CleanupStack::PushL(charFormatLayer);
		CRichText* richText = CRichText::NewL(paraFormatLayer, charFormatLayer);
		CleanupStack::PushL(richText);

		TInt pos = richText->DocumentLength();
		richText->InsertL(pos, messDes);

		TMsvEntry newBioEntry;
		newBioEntry.SetNew(ETrue);
		newBioEntry.SetComplete(EFalse);
		newBioEntry.SetUnread(ETrue);
		newBioEntry.SetVisible(ETrue);
		newBioEntry.SetReadOnly(EFalse);
		newBioEntry.SetFailed(EFalse);
		newBioEntry.SetOperation(EFalse);
		newBioEntry.SetMultipleRecipients(EFalse);
		newBioEntry.SetAttachment(EFalse);
		newBioEntry.iMtm = KUidBIOMessageTypeMtm;
		newBioEntry.iType = KUidMsvMessageEntry;
		newBioEntry.iServiceId = iBioServiceId;
		TTime now;
		now.UniversalTime();
		newBioEntry.iDate = now;

		TTime unixEpoch(KUnixEpoch);
		TTimeIntervalSeconds seconds;
		TTime timeStamp = newBioEntry.iDate;
		timeStamp.SecondsFrom(unixEpoch, seconds);
		retTimeStamp.setTime_t(seconds.Int());

		newBioEntry.iDescription.Set(richText->Read(0, richText->DocumentLength()));
		TBufC<KTelephoneNumberMaxLength> telNumber;

		QString recepient(TEST_MSG_FROM1);
		tempNumber = XQConversions::qStringToS60Desc(recepient);

		telNumber = tempNumber->Des();
		newBioEntry.iDetails.Set(telNumber);

		SetForMtmTypeL(newBioEntry, aMessageType);

		newBioEntry.iSize = richText->DocumentLength();// msgSize;
		CreateBioEntryClientSideL(newBioEntry, *richText);

		CleanupStack::PopAndDestroy(4); // richText, charFormatLayer, paraFormatLayer, localBuffer
		return newBioEntry.Id();
}
// ---------------------------------------------------------
// MsgStoreHandler::HandleClass0SmsL()
// ---------------------------------------------------------
//
void MsgStoreHandler::HandleClass0SmsL(CMsvEntry* aMsgEntry, TMsvId aMsgId)
{
    CleanupStack::PushL(aMsgEntry);

    CMsvStore* store = aMsgEntry->ReadStoreL();
    CleanupStack::PushL(store);

    CParaFormatLayer* paraFormatLayer = CParaFormatLayer::NewL();
    CleanupStack::PushL(paraFormatLayer);

    CCharFormatLayer* charFormatLayer = CCharFormatLayer::NewL();
    CleanupStack::PushL(charFormatLayer);

    CRichText* richText = CRichText::NewL(paraFormatLayer, charFormatLayer);
    CleanupStack::PushL(richText);

    store->RestoreBodyTextL(*richText);

    TInt len = richText->DocumentLength();
    HBufC* bufBody = HBufC::NewLC(len * 2);

    // Get Body content of SMS message
    TPtr bufBodyPtr = bufBody->Des();
    richText->Extract(bufBodyPtr, 0, len);

    //convert bufbody to qstring..
    QString body = XQConversions::s60DescToQString(*bufBody);

    Class0Info class0Info;

    class0Info.body = body;
    CleanupStack::PopAndDestroy(bufBody);

    // Get From address of SMS message
    CPlainText* nullString = CPlainText::NewL();
    CleanupStack::PushL(nullString);

    CSmsHeader* smsheader = CSmsHeader::NewL(CSmsPDU::ESmsDeliver, *nullString);
    CleanupStack::PushL(smsheader);
    smsheader->RestoreL(*store);

    QString address = XQConversions::s60DescToQString(smsheader->FromAddress());
    class0Info.address = address;

    // Get alias of SMS message
    QString alias;
    int count;
    MsgContactHandler::resolveContactDisplayName(address, alias, count);
    class0Info.alias = alias;

    // Get timestamp of SMS message
    QDateTime timeStamp;
    TTime time = aMsgEntry->Entry().iDate;
    TTime unixEpoch(KUnixEpoch);
    TTimeIntervalSeconds seconds;
    time.SecondsFrom(unixEpoch, seconds);
    timeStamp.setTime_t(seconds.Int());

    const QString times = timeStamp.toString("dd/MM/yy hh:mm ap");
    class0Info.time = times;

    class0Info.messageId = aMsgId;
    CleanupStack::PopAndDestroy(7);
    aMsgEntry = NULL;

    // Show the SMS message..  
    iNotifier->ShowClass0Message(class0Info);
}