Beta merge 2
[profile/ivi/wrt-plugins-tizen.git] / src / platform / Tizen / Messaging / Messaging.cpp
1 /*
2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License. 
15 */
16
17
18 /**
19  *
20  *
21  * @file       Messaging.cpp
22  * @author     Pawel Misiak (p.misiak@samsung.com)
23  * @version    0.1
24  * @brief
25  */
26 #include <emf-types.h>
27 #include <Emf_Mapi.h>
28
29 #include <Commons/Exception.h>
30 #include <Commons/StringUtils.h>
31 #include <dpl/log/log.h>
32 #include <dpl/scoped_free.h>
33 #include "Messaging.h"
34 #include "Sms.h"
35 #include "Mms.h"
36 #include "BinarySms.h"
37 #include "Email.h"
38 #include "EmailConverter.h"
39
40 #include "API/Messaging/log.h"
41
42
43
44 #include "API/Messaging/StorageChangesMessageFilterValidatorFactory.h"
45 #include "API/Messaging/StorageChangesConversationFilterValidatorFactory.h"
46 #include "API/Messaging/StorageChangesFolderFilterValidatorFactory.h"
47 #include "MessageQueryGenerator.h"
48
49 #include "ConversationQueryGenerator.h"
50 #include "FolderQueryGenerator.h"
51
52 #include "messageDB/MessageStorageReader.h"
53
54 extern "C" {
55 #include <MapiStorage.h>
56 #include <MapiControl.h>
57 #include <MsgMmsTypes.h>
58 #include <MapiTransport.h>
59 #include <MapiMessage.h>
60 }
61
62 #include <Commons/ThreadPool.h>
63 #include "Conversation.h"
64 #include "MessageFolder.h"
65
66
67 #define LOG_ENTER LogDebug("---> ENTER");
68 #define LOG_EXIT LogDebug("---> EXIT");
69
70
71 using namespace std;
72 using namespace TizenApis::Api::Messaging;
73 using namespace TizenApis::Api::Tizen;
74 using namespace WrtDeviceApis::Commons;
75
76 namespace {
77 const char* DBUS_INTERFACE_EMAIL_RECEIVED = "User.Email.StorageChange";
78 const char* DBUS_FILTER_EMAIL_RECEIVED =
79     "type='signal',interface='User.Email.StorageChange'";
80
81 const int MESSAGE_FIND_LIMIT = 100;
82 }
83
84 namespace TizenApis {
85 namespace Platform {
86 namespace Messaging {
87
88 int Messaging::m_currentEmailAccountId = 0;
89 DPL::Atomic Messaging::m_objCounter;
90
91 Messaging& Messaging::getInstance()
92 {
93     static Messaging instance;
94     return instance;
95 }
96
97 Messaging::Messaging() :
98     m_onMessageReceivedHandleMgr(NULL),
99     m_dbusConnection(new DBus::Connection()),
100     m_dbusWorkerThread(new DPL::Thread())
101 {
102     Try
103     {
104         const vector<Api::Messaging::EmailAccountInfo> accounts = getEmailAccounts();
105         LogDebug("Number of emails account=" << accounts.size());
106         if (accounts.size() > 0) {
107             // set default email account - first from the list
108             setCurrentEmailAccount(accounts[0]);
109         } else {
110             LogError("no default email account set");
111         }
112     }
113
114     Catch(WrtDeviceApis::Commons::PlatformException) {
115         LogError("No email accounts available");
116     }
117
118     Catch(WrtDeviceApis::Commons::InvalidArgumentException) {
119         LogError("No email accounts available");
120         //current email not configured, skipped
121     }
122
123     Catch(WrtDeviceApis::Commons::UnknownException) {
124         LogError("unknown error");
125     }
126
127     // Begin service for email management ?? pmi question if it should be added before email actions
128     if (0 == m_objCounter) {
129         int error = email_service_begin();
130         if (EMF_ERROR_NONE != error) {
131             LogError("email_service_begin() returned error " << error);
132         } else {
133             LogInfo("email_service_begin() executed without error");
134         }
135     }
136     ++m_objCounter;
137
138     m_dbusWorkerThread->Run();
139     m_dbusConnection->setWorkerThread(m_dbusWorkerThread);
140     m_dbusConnection->addFilter(DBUS_FILTER_EMAIL_RECEIVED);
141     m_dbusConnection->AddListener(this);
142 }
143
144 Messaging::~Messaging()
145 {
146     // Endservice for email management
147     m_dbusConnection->RemoveListener(this);
148     m_dbusConnection->setWorkerThread(NULL);
149     m_dbusWorkerThread->Quit();
150     delete m_dbusWorkerThread;
151
152     if (!--m_objCounter) {
153         int error = email_service_end();
154         if (EMF_ERROR_NONE != error) {
155             LogError("email_service_end() returned error " << error);
156         } else {
157             LogDebug("email_service_end() executed without error");
158         }
159     }
160 }
161
162 void Messaging::getNumberOfMessages(MessageType msgType,
163         FolderType folder,
164         int* readed,
165         int* unReaded)
166 {
167     if (NULL == readed ||
168         NULL == unReaded) {
169         LogError("output pointers are NULL");
170         Throw(WrtDeviceApis::Commons::InvalidArgumentException);
171     }
172     *readed = 0;
173     *unReaded = 0;
174     if (Api::Messaging::SMS == msgType) {
175         getNumberOfSms(folder, readed, unReaded);
176     } else if (Api::Messaging::MMS == msgType) {
177         getNumberOfMms(folder, readed, unReaded);
178     } else if (Api::Messaging::EMAIL == msgType) {
179         getNumberOfEmails(folder, readed, unReaded);
180     } else {
181         LogError("wrong message type");
182         Throw(WrtDeviceApis::Commons::PlatformException);
183     }
184 }
185
186 vector<IMessagePtr> Messaging::findMessages(const vector<MessageType>& msgTypes,
187         const string &folder,
188         const Api::Tizen::FilterPtr& filter)
189 {
190     LogDebug("enter");
191     vector<IMessagePtr> retVal;
192     back_insert_iterator< vector<IMessagePtr> > biit(retVal);
193     vector<MessageType>::const_iterator it = msgTypes.begin();
194     for (; it != msgTypes.end(); ++it) {
195         LogDebug("Finding messages (" << *it << ")  in folder: " << folder);
196         vector<IMessagePtr> result;
197
198         switch (*it) {
199         case SMS:
200         {
201             FolderType folderEnum = Sms::toFolder(folder);
202             result = findSms(folderEnum, filter);
203             break;
204         }
205         case MMS:
206         {
207             FolderType folderEnum = Mms::toFolder(folder);
208             result = findMms(folderEnum, filter);
209             break;
210         }
211         case EMAIL:
212         {
213             result = findEmail(folder, filter);
214             break;
215         }
216         default:
217             LogError("message type unknown");
218             Throw(WrtDeviceApis::Commons::PlatformException);
219         }
220         LogDebug("Found: " << result.size());
221         copy(result.begin(), result.end(), biit);
222     }
223
224     return retVal;
225 }
226
227 std::string Messaging::generateFilterSql(const Api::Tizen::FilterPtr& filter){
228         LogDebug("<<<");
229         std::string filterSql;
230
231         MessageQueryGeneratorPtr queryGenerator(new MessageQueryGenerator());
232         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
233         filter->travel(filterVisitor, 0);
234         filterSql = queryGenerator->getQuery();
235
236         LogDebug(">>> filterSql:[" << filterSql << "]");
237         return filterSql;
238 }
239
240         vector<IMessagePtr> Messaging::findMessages(const vector<MessageType>& msgTypes, FolderType folder,
241                         const Api::Tizen::FilterPtr& filter)
242 {
243         LogDebug("enter");
244         vector<IMessagePtr> retVal;
245         back_insert_iterator< vector<IMessagePtr> > biit(retVal);
246
247         std::string filterSql = generateFilterSql(filter);
248
249
250
251         vector<MessageType>::const_iterator it = msgTypes.begin();
252         for (; it != msgTypes.end(); ++it) {
253                 LogDebug("Finding messages (" << *it << ")  in folder: " << folder);
254                 vector<IMessagePtr>(Messaging::*findFnPtr)(Api::Messaging::FolderType folder, const Api::Tizen::FilterPtr& filter) = NULL;
255
256                 switch (*it) {
257                         case SMS:
258                         {
259                                 findFnPtr = &Messaging::findSms;
260                                 break;
261                         }
262                         case MMS:
263                         {
264                                 findFnPtr = &Messaging::findMms;
265                                 break;
266                         }
267                         case EMAIL:
268                         {
269                                 findFnPtr = &Messaging::findEmail;
270                                 break;
271                         }
272                         default:
273                         LogError("message type unknown");
274                         Throw(WrtDeviceApis::Commons::PlatformException);
275                 }
276
277                 vector<IMessagePtr> result = (this->*findFnPtr)(folder, filter);
278                 LogDebug("Found: " << result.size());
279                 copy(result.begin(), result.end(), biit);
280         }
281
282         return retVal;
283 }
284
285         void Messaging::printErrorMessage(int errorCode){
286                 switch(errorCode){
287                         case EMF_ERROR_MAIL_NOT_FOUND:{
288                                 LogDebug("EMF_ERROR_MAIL_NOT_FOUND");
289                                 break;
290                         }
291                         case EMF_ERROR_DB_FAILURE:{
292                                 LogDebug("EMF_ERROR_DB_FAILURE");
293                                 break;
294                         }
295                         default:{
296                                 LogDebug("other error message:" << errorCode);
297                 }
298         }
299         }
300
301         vector<IMessagePtr> Messaging::createVectorFromeMessageList(const MSG_LIST_S& message_list){
302                 LogDebug("<<<");
303
304                 vector<IMessagePtr> retVal;
305                 LogDebug("message_list.nCount:" << message_list.nCount);
306                 for (int i = 0; i < message_list.nCount; i++) {
307 //                      int msgId = msg_get_message_id(message_list.msgInfo[i]);
308
309                         string addressVal = msg_get_ith_address(message_list.msgInfo[i], 0);
310                         LogDebug("<<< addressVal:" << addressVal);
311
312                         int msgType = msg_get_message_type(message_list.msgInfo[i]);
313                         MessageType webApiMsgType;
314
315                         switch(msgType){
316                                 case    MSG_TYPE_SMS:{
317                                         webApiMsgType = Api::Messaging::SMS;
318                                         break;
319                                 }
320                                 case MSG_TYPE_MMS:{
321                                         webApiMsgType = Api::Messaging::MMS;
322                                         break;
323                                 }
324                                 default:{
325                                         LogError("[ERROR]invalid message type:" << msgType);
326                                         continue;
327                                 }
328                         }
329
330                         int l_msgId = msg_get_message_id(message_list.msgInfo[i]);
331                         Api::Messaging::IMessagePtr msg;
332                         msg = MessageFactory::createMessage(webApiMsgType, l_msgId);
333                         retVal.push_back(msg);
334                 }       //for
335
336                 LogDebug(">>>");
337                 return retVal;
338         }
339
340         std::vector<Api::Messaging::IConversationPtr> Messaging::createVectorFromeThreadViewList(const MSG_THREAD_VIEW_LIST_S& threadViewList){
341                 vector<IConversationPtr> recVec;
342
343                 if (threadViewList.nCount <= 0) {
344                         LogDebug("Empty...");
345                 }       else    {
346                         for (int i = 0; i < threadViewList.nCount; i++)         {
347 //                              Api::Messaging::IConversationPtr convPtr(new Conversation(i));
348                                 Api::Messaging::IConversationPtr convPtr(new Conversation(threadViewList.msgThreadInfo[i]));
349
350                                 recVec.push_back(convPtr);
351                         }
352                 }
353
354                 return recVec;
355         }
356
357         vector<IMessagePtr> Messaging::querySmsMmsMessages(const std::string& queryString){
358                 LogDebug("<<< queryString:[" << queryString <<"]");
359
360                 vector<IMessagePtr> retVal;
361                 MSG_LIST_S message_list = {0, NULL};
362
363                 Try{
364                         MSG_ERROR_T res = MSG_ERR_UNKNOWN;
365
366                         MessageStorageReader reader;
367                         reader.MsgStoConnectDB();
368                         res = reader.queryMessage(queryString, &message_list);
369
370                         if (MSG_SUCCESS != res) {
371                                 LogError("msg_get_folder_view_list failed " << res);
372                                 Throw(WrtDeviceApis::Commons::PlatformException);
373                         }
374                         reader.MsgStoDisconnectDB();
375
376                         retVal = createVectorFromeMessageList(message_list);
377
378                         msg_release_message_list(&message_list);
379                 }Catch(WrtDeviceApis::Commons::PlatformException) {
380                         LogError("Problem with message creation, cleaning");
381                         if (message_list.nCount) {
382                                 msg_release_message_list(&message_list);
383                         }
384                         throw;
385                 }       //Catch
386
387                 LogDebug(">>>");
388                 return retVal;
389         }
390
391 vector<IConversationPtr> Messaging::querySmsMmsConversation(const std::string& sqlWhereClause){
392         LogDebug("sqlWhereClause:[" << sqlWhereClause << "]");
393
394         std::vector<Api::Messaging::IConversationPtr> recVec;
395         MSG_THREAD_VIEW_LIST_S threadViewList;
396
397         MSG_ERROR_T res = MSG_ERR_UNKNOWN;
398
399         MessageStorageReader reader;
400         reader.MsgStoConnectDB();
401         res = reader.queryConversation(sqlWhereClause, &threadViewList);
402
403         if (MSG_SUCCESS != res) {
404                 LogError("queryConversation failed:" << res);
405                 Throw(WrtDeviceApis::Commons::PlatformException);
406         }
407         reader.MsgStoDisconnectDB();
408
409         recVec = createVectorFromeThreadViewList(threadViewList);
410
411         msg_release_thread_view_list(&threadViewList);
412
413         LogDebug(">>>");
414         return recVec;
415 }
416
417 vector<IConversationPtr> Messaging::queryEmailConversation(const std::string& sqlWhereClause){
418         LogDebug("sqlWhereClause:[" << sqlWhereClause << "]");
419
420         std::vector<Api::Messaging::IConversationPtr> emailResultVector;
421         emf_mail_list_item_t* mailList = NULL;
422         int mailListCount = 0;
423         int errCode = 0;
424         errCode = email_query_message_ex(const_cast<char*>(sqlWhereClause.c_str()), &mailList, &mailListCount);
425
426         if(errCode != EMF_ERROR_NONE){
427                 LogError("[ERROR]email_query_message_ex failed:" << errCode);
428                 printErrorMessage(errCode);
429                 if (mailList != NULL){
430                         free(mailList);
431                 }
432         }else{
433                 LogDebug("message found mailListCount:" << mailListCount);
434                 std::map<int, int> checkUnique;
435
436                 for(int i=0; i<mailListCount; i++){
437                         if (checkUnique.find(mailList[i].thread_id) == checkUnique.end()){
438                                 checkUnique[mailList[i].thread_id] = mailList[i].thread_id;
439                                 Api::Messaging::IConversationPtr convPtr(new Conversation(mailList[i].thread_id, Api::Messaging::EMAIL));
440
441                                 //TODO for debug
442                                 LogDebug("mailList[i].thread_id:[" << mailList[i].thread_id << "]");                            
443                                 LogDebug("mailList[i].from:[" << mailList[i].from << "]");
444                                 LogDebug("mailList[i].from_email_address : [" << mailList[i].from_email_address <<"]");
445                                 LogDebug("mailList[i].datetime:[" << mailList[i].datetime << "]");
446                                 LogDebug("mailList[i].subject:[" << mailList[i].subject << "]");
447                                 LogDebug("mailList[i].mailbox_name:[" << mailList[i].mailbox_name << "]");
448                                 LogDebug("mailList[i].previewBodyText:[" << mailList[i].previewBodyText << "]");
449                                 LogDebug("mailList[i].flags_seen_field:[" << mailList[i].flags_seen_field << "]");
450                                 LogDebug("mailList[i].priority:[" << mailList[i].priority<< "]");
451
452                                 if (convPtr->getResult() == true)
453                                 {
454                                         emailResultVector.push_back(convPtr);
455                                 }
456                         }       //if
457                 }//for
458         }//if
459
460         if (mailList != NULL){
461                 free(mailList);
462         }
463
464         LogDebug(">>>");
465         return emailResultVector;
466 }
467
468 vector<IMessagePtr> Messaging::queryEmailMessage(const std::string& sqlWhereClause){
469         LogDebug("sqlWhereClause:[" << sqlWhereClause << "]");
470
471         vector<IMessagePtr> emailResultVector;
472
473         emf_mail_list_item_t* mailList = NULL;
474         int mailListCount = 0;
475         int errCode = 0;
476         errCode = email_query_message_ex(const_cast<char*>(sqlWhereClause.c_str()), &mailList, &mailListCount);
477
478         if(errCode != EMF_ERROR_NONE){
479                 LogError("[ERROR]email_query_message_ex failed:" << errCode);
480                 printErrorMessage(errCode);
481                 if (mailList != NULL)           {
482                         free(mailList);
483                 }
484         }else{
485                 LogDebug("message found mailListCount:" << mailListCount);
486
487                 for(int i=0; i<mailListCount; i++){
488                         //Api::Messaging::IMessagePtr msg = MessageFactory::createMessage(EMAIL, mailList[i].mail_id);
489                         Api::Messaging::IMessagePtr msg = MessageFactory::createEmailMessage(mailList[i].account_id, mailList[i].mail_id);
490                         
491                         //TODO for debug
492                         LogDebug("mailList[i].from:[" << mailList[i].from << "]");
493                         LogDebug("mailList[i].from_email_address : [" << mailList[i].from_email_address <<"]");
494                         LogDebug("mailList[i].datetime:[" << mailList[i].datetime << "]");
495                         LogDebug("mailList[i].subject:[" << mailList[i].subject << "]");
496                         LogDebug("mailList[i].mailbox_name:[" << mailList[i].mailbox_name << "]");
497                         LogDebug("mailList[i].previewBodyText:[" << mailList[i].previewBodyText << "]");
498                         LogDebug("mailList[i].flags_seen_field:[" << mailList[i].flags_seen_field << "]");
499                         LogDebug("mailList[i].priority:[" << mailList[i].priority<< "]");
500
501                         emailResultVector.push_back(msg);
502                 }//for
503         }//if
504
505         if (mailList != NULL)           {
506                 free(mailList);
507         }
508
509         LogDebug(">>>");
510         return emailResultVector;
511 }
512
513 vector<IMessagePtr> Messaging::findMessages(const Api::Tizen::FilterPtr& filter){
514         LogDebug("<<<");
515
516         vector<IMessagePtr> retVal;
517         std::string filterSql;
518
519         MessageQueryGeneratorPtr queryGenerator(new MessageQueryGenerator());
520
521         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
522         filter->travel(filterVisitor, 0);
523         filterSql = queryGenerator->getQuery();
524         LogDebug("filterSql:[" << filterSql <<"]");
525
526         int messageType = queryGenerator->getMessageType();
527         switch(messageType){
528                 case Api::Messaging::EMAIL:
529                         LogDebug("message type is EMAIL:[" << messageType <<"]");
530                         retVal = queryEmailMessage(filterSql);
531                         break;
532
533                 case Api::Messaging::SMS:
534                 case Api::Messaging::MMS:
535                         LogDebug("message type is SMS or MMS:[" << messageType <<"]");
536                         queryGenerator->reset(MessageQueryGenerator::MODE_SMS_MMS);
537                         filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
538                         filter->travel(filterVisitor);
539                         filterSql = queryGenerator->getQuery();
540                         retVal = querySmsMmsMessages(filterSql);
541                         break;
542
543                 default:
544                         LogError("[ERROR] >>> invlid message type:[" << messageType <<"]");
545                         return retVal;
546         }
547
548         LogDebug(">>>");
549         return retVal;
550 }
551
552 //TODO refactoring
553 vector<IMessagePtr> Messaging::findMessages(const Api::Tizen::FilterPtr& filter, const Api::Tizen::SortModePtr& sortMode, const long limit, const long offset)
554 {
555         LogDebug("<<<");
556
557         vector<IMessagePtr> retVal;
558         std::string filterSql;
559
560         MessageQueryGeneratorPtr queryGenerator(new MessageQueryGenerator(sortMode, limit, offset));
561
562         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
563         filter->travel(filterVisitor, 0);
564         filterSql = queryGenerator->getQuery();
565         LogDebug("filterSql:[" << filterSql <<"]");
566
567         int messageType = queryGenerator->getMessageType();
568         switch(messageType){
569                 case Api::Messaging::EMAIL:
570                         LogDebug("message type is EMAIL:[" << messageType <<"]");
571                         retVal = queryEmailMessage(filterSql);
572                         break;
573
574                 case Api::Messaging::SMS:
575                 case Api::Messaging::MMS:
576                         LogDebug("message type is SMS or MMS:[" << messageType <<"]");
577                         queryGenerator->reset(MessageQueryGenerator::MODE_SMS_MMS);
578                         filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
579                         filter->travel(filterVisitor);
580                         filterSql = queryGenerator->getQuery();
581                         retVal = querySmsMmsMessages(filterSql);
582                         break;
583
584                 default:
585                         MsgLogError("[ERROR] >>> invlid message type:[" << messageType <<"]");
586                         return retVal;
587         }
588
589         LogDebug(">>>");
590         return retVal;
591 }
592
593 vector<string> Messaging::getMessageIds(MessageType msgType,
594         FolderType folder)
595 {
596     switch (msgType) {
597     case SMS:
598         return getSmsIds(folder);
599     case MMS:
600         return getMmsIds(folder);
601     case EMAIL:
602         return getEmailIds(folder);
603     default:
604         LogError("not supported message type");
605         Throw(WrtDeviceApis::Commons::InvalidArgumentException);
606     }
607 }
608
609 vector<string> Messaging::getSmsIds(FolderType folder)
610 {
611     vector<string> retVal;
612     msg_message_t msg = msg_new_message();
613     MSG_LIST_S folder_list_view = { 0, NULL };
614
615     Try
616     {
617         const MSG_SORT_RULE_S sort_rules = { MSG_SORT_BY_DISPLAY_TIME, true };
618         MSG_ERROR_T res = MSG_ERR_UNKNOWN;
619         const MSG_FOLDER_ID_T platformFolder = convertFolderToPlatform(folder);
620         res = msg_get_folder_view_list(
621                 MsgGetCommonHandle(), platformFolder, &sort_rules,
622                 &folder_list_view);
623
624         if (MSG_SUCCESS != res) {
625             LogError("msg_Get_folder_view_list failed" << res);
626             Throw(WrtDeviceApis::Commons::PlatformException);
627         }
628
629         for (int i = 0; i < folder_list_view.nCount; i++) {
630             if (MSG_TYPE_SMS ==
631                                 msg_get_message_type(folder_list_view.
632                                                      msgInfo[i])) {
633                                 int l_msgId = msg_get_message_id(
634                         folder_list_view.msgInfo[i]);
635                 ostringstream stream;
636                 stream << l_msgId;
637                 retVal.push_back(stream.str());
638             }
639         }
640
641                 msg_release_message_list(&folder_list_view);
642     }
643
644     Catch(WrtDeviceApis::Commons::PlatformException) {
645         LogError("Problem with message creation, cleaning");
646         if (folder_list_view.nCount) {
647                         msg_release_message_list(&folder_list_view);
648         }
649         if (msg) {
650             msg_release_message(&msg);
651         }
652         throw;
653     }
654
655     return retVal;
656 }
657
658 vector<string> Messaging::getMmsIds(FolderType folder)
659 {
660     vector<string> retVal;
661     msg_message_t msg = msg_new_message();
662     MSG_LIST_S folder_list_view = { 0, NULL };
663
664     Try
665     {
666         const MSG_SORT_RULE_S sort_rules = { MSG_SORT_BY_DISPLAY_TIME, true };
667         MSG_ERROR_T res = MSG_ERR_UNKNOWN;
668         const MSG_FOLDER_ID_T platformFolder = convertFolderToPlatform(folder);
669         res = msg_get_folder_view_list(
670                 MsgGetCommonHandle(), platformFolder, &sort_rules,
671                 &folder_list_view);
672
673         if (MSG_SUCCESS != res) {
674             LogError("msg_Get_folder_view_list failed" << res);
675             Throw(WrtDeviceApis::Commons::PlatformException);
676         }
677
678         for (int i = 0; i < folder_list_view.nCount; i++) {
679             if (MSG_TYPE_MMS ==
680                                 msg_get_message_type(folder_list_view.
681                                                      msgInfo[i])) {
682                                 int l_msgId = msg_get_message_id(
683                         folder_list_view.msgInfo[i]);
684                 ostringstream stream;
685                 stream << l_msgId;
686                 retVal.push_back(stream.str());
687             }
688         }
689
690                 msg_release_message_list(&folder_list_view);
691     }
692
693     Catch(WrtDeviceApis::Commons::PlatformException) {
694         LogError("Problem with message creation, cleaning");
695         if (folder_list_view.nCount) {
696                         msg_release_message_list(&folder_list_view);
697         }
698         if (msg) {
699             msg_release_message(&msg);
700         }
701         throw;
702     }
703
704     return retVal;
705 }
706
707 vector<string> Messaging::getEmailIds(FolderType folder)
708 {
709     vector<string> retVal;
710
711     //TODO
712     LogError("TODO");
713     Throw(WrtDeviceApis::Commons::UnknownException);
714
715     return retVal;
716 }
717
718 vector<EmailAccountInfo> Messaging::getEmailAccounts() const
719 {
720     emf_account_t* accounts = NULL;
721     int count = 0;
722     Try {
723         if (!email_get_account_list(&accounts, &count)) {
724             ThrowMsg(WrtDeviceApis::Commons::PlatformException,
725                      "Couldn't get e-mail accounts.");
726         }
727
728         if (0 == count) {
729             ThrowMsg(WrtDeviceApis::Commons::PlatformException, "No e-mail account found.");
730         }
731
732         vector<Api::Messaging::EmailAccountInfo> result;
733         for (int i = 0; i < count; ++i) {
734             Api::Messaging::EmailAccountInfo account(accounts[i].account_id,
735                                           accounts[i].user_name,
736                                           accounts[i].email_addr);
737             result.push_back(account);
738         }
739
740         if (accounts != NULL) {
741             email_free_account(&accounts, count);
742         }
743
744         return result;
745     }
746     Catch(WrtDeviceApis::Commons::PlatformException) {
747         if (accounts != NULL) {
748             email_free_account(&accounts, count);
749         }
750         throw;
751     }
752 }
753
754 int Messaging::getEmailAccountId(const std::string& account)
755 {
756     int retVal = 0;
757     string tmpAccount = account;
758     emf_account_t *pAccountArray = NULL;
759     int iCount = 0;
760
761     Try
762     {
763         if (account.empty()) {
764             tmpAccount = getCurrentEmailAccount().getAddress();
765             if (tmpAccount.empty()) {
766                 LogError(
767                     "current email account is not set, possible that no account created");
768                 Throw(WrtDeviceApis::Commons::PlatformException);
769             }
770         }
771
772         if (!email_get_account_list(&pAccountArray, &iCount)) {
773             LogError("email_get_account_list error");
774             Throw(WrtDeviceApis::Commons::PlatformException);
775         }
776
777         if (0 == iCount) {
778             LogError("no email account exist");
779             Throw(WrtDeviceApis::Commons::PlatformException);
780         }
781
782         for (int i = 0; i < iCount; i++) {
783             string tmp = pAccountArray[i].email_addr;
784             if (tmp == tmpAccount) {
785                 m_currentEmailAccountId = pAccountArray[i].account_id;
786                 retVal = m_currentEmailAccountId;
787                 break;
788             }
789         }
790
791         if (0 == m_currentEmailAccountId) {
792             LogError("wrong email account ID");
793             Throw(WrtDeviceApis::Commons::PlatformException);
794         }
795
796         if (pAccountArray != NULL) {
797             LogDebug("free account, ptr=" << pAccountArray);
798             email_free_account(&pAccountArray, iCount);
799         }
800
801         if (0 == retVal) {
802             LogError("no email account created");
803             Throw(WrtDeviceApis::Commons::PlatformException);
804         }
805     }
806
807     Catch(WrtDeviceApis::Commons::PlatformException) {
808         LogError("exception catch, platform exception");
809         if (pAccountArray != NULL) {
810             email_free_account(&pAccountArray, iCount);
811         }
812         throw;
813     }
814
815     return retVal;
816 }
817
818 void Messaging::fetchEmailHeaders()
819 {
820     emf_mailbox_t *mailbox = NULL;
821     unsigned handle = 0;
822     mailbox = static_cast<emf_mailbox_t*>(calloc(sizeof (emf_mailbox_t), 1));
823     if (!mailbox) {
824         LogError("calloc failed");
825         return;
826     }
827     mailbox->account_id = m_currentEmailAccountId;
828     mailbox->name = strdup(EMF_INBOX_NAME);
829     if (EMF_ERROR_NONE != email_sync_header(mailbox, &handle)) {
830         LogError("email_sync_header failed");
831     }
832     email_free_mailbox(&mailbox, 1);
833 }
834
835 int Messaging::convertFolderToPlatform(const FolderType folder)
836 {
837     MSG_FOLDER_ID_T platfromFolderId;
838     switch (folder) {
839     case INBOX:
840         platfromFolderId = MSG_INBOX_ID;
841         break;
842     case DRAFTBOX:
843         platfromFolderId = MSG_DRAFT_ID;
844         break;
845     case OUTBOX:
846         platfromFolderId = MSG_OUTBOX_ID;
847         break;
848     case SENTBOX:
849         platfromFolderId = MSG_SENTBOX_ID;
850         break;
851     case SPAMBOX:
852     // intentionally not break in platform is no spambox
853     default:
854         LogError("Invalid folder: " << folder);
855         Throw(WrtDeviceApis::Commons::PlatformException);
856     }
857
858     return platfromFolderId;
859 }
860
861 int Messaging::convertFolderToPlatform(const std::string &folder)
862 {
863     MSG_FOLDER_LIST_S folderList = { 0, NULL };
864     int result = 0;
865     Try
866     {
867         if (MSG_SUCCESS !=
868             msg_get_folder_list(MsgGetCommonHandle(), &folderList)) {
869             LogError("msg_get_folder_list error");
870             Throw(WrtDeviceApis::Commons::PlatformException);
871         }
872         for (int i = 0; i < folderList.nCount; ++i) {
873             if (MSG_FOLDER_TYPE_USER_DEF ==
874                 folderList.folderInfo[i].folderType &&
875                 NULL != folderList.folderInfo[i].folderName &&
876                 folder == folderList.folderInfo[i].folderName) {
877                 result = folderList.folderInfo[i].folderId;
878                 break;
879             }
880         }
881     }
882     Catch(WrtDeviceApis::Commons::PlatformException) {
883         if (folderList.nCount) {
884             msg_release_folder_list(&folderList);
885         }
886         throw;
887     }
888     if (folderList.nCount) {
889         msg_release_folder_list(&folderList);
890     }
891     return result;
892 }
893
894 void Messaging::addOnMessageReceived(
895         const Api::Messaging::EmitterMessageReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, int funtionIndex)
896 {
897     LogDebug("ENTER");
898
899     if(filter != NULL)
900     {
901         Try
902         {
903             LogDebug("funtionIndex = " << funtionIndex);    
904             bool isValidFilter = validateFilter(filter, funtionIndex);
905             if(isValidFilter == false){
906                 LogError("[ERROR]this filter is invalid");
907                 Throw(WrtDeviceApis::Commons::InvalidArgumentException);
908             }    
909         }
910         Catch(WrtDeviceApis::Commons::PlatformException) {
911             throw;
912         }
913     }else
914     {
915         LogDebug("filter is NULL");     
916     }
917
918         
919     m_onMessageReceived.attach(emitter);
920     EmittersMessageReceived::LockType lock = m_onMessageReceived.getLock();
921     if ((m_onMessageReceived.size() == 1)&&((m_onConversationReceived.size() + m_onFolderReceived.size()) == 0)) {
922         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(
923                 new MsgServiceHandleMgr());
924         int err;
925
926         err = msg_reg_storage_change_callback(
927         m_onMessageReceivedHandleMgr->getHandle(),
928         onMessageStorageChanged,
929         this);
930
931         if (err != MSG_SUCCESS) {
932             LogError("Couldn't register on MMS received callback, err=" << err);
933         }
934
935         m_dbusConnection->open(DBUS_BUS_SYSTEM);
936     }
937 }
938
939 void Messaging::addOnMessageReceived(
940         const Api::Messaging::EmitterConversationReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, int funtionIndex)
941 {
942     LogDebug("ENTER");
943
944     if(filter != NULL)
945     {
946         Try
947         {
948             LogDebug("funtionIndex = " << funtionIndex);    
949             bool isValidFilter = validateFilter(filter, funtionIndex);
950             if(isValidFilter == false){
951                 LogError("[ERROR]this filter is invalid");
952                 Throw(WrtDeviceApis::Commons::InvalidArgumentException);
953             }    
954         }
955         Catch(WrtDeviceApis::Commons::PlatformException) {
956             throw;
957         }
958     }else
959     {
960         LogDebug("filter is NULL");     
961     }
962
963         
964     m_onConversationReceived.attach(emitter);
965     EmittersConversationReceived::LockType lock = m_onConversationReceived.getLock();
966     if ((m_onConversationReceived.size() == 1)&&((m_onMessageReceived.size() + m_onFolderReceived.size()) == 0)) {
967         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(
968                 new MsgServiceHandleMgr());
969         int err;
970
971         err = msg_reg_storage_change_callback(
972         m_onMessageReceivedHandleMgr->getHandle(),
973         onMessageStorageChanged,
974         this);
975
976         if (err != MSG_SUCCESS) {
977             LogError("Couldn't register on MMS received callback, err=" << err);
978         }
979
980         m_dbusConnection->open(DBUS_BUS_SYSTEM);
981     }
982 }
983
984 void Messaging::addOnMessageReceived(
985         const Api::Messaging::EmitterFolderReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, int funtionIndex)
986 {
987     LogDebug("ENTER");
988
989     if(filter != NULL)
990     {
991         Try
992         {
993             LogDebug("funtionIndex = " << funtionIndex);    
994             bool isValidFilter = validateFilter(filter, funtionIndex);
995             if(isValidFilter == false){
996                 LogError("[ERROR]this filter is invalid");
997                 Throw(WrtDeviceApis::Commons::InvalidArgumentException);
998             }    
999         }
1000         Catch(WrtDeviceApis::Commons::PlatformException) {
1001             throw;
1002         }
1003     }else
1004     {
1005         LogDebug("filter is NULL");     
1006     }
1007
1008         
1009     m_onFolderReceived.attach(emitter);
1010     EmittersFolderReceived::LockType lock = m_onFolderReceived.getLock();
1011     if ((m_onFolderReceived.size() == 1)&&((m_onMessageReceived.size() + m_onConversationReceived.size()) == 0)) {
1012         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(
1013                 new MsgServiceHandleMgr());
1014         int err;
1015
1016         err = msg_reg_storage_change_callback(
1017         m_onMessageReceivedHandleMgr->getHandle(),
1018         onMessageStorageChanged,
1019         this);
1020
1021         if (err != MSG_SUCCESS) {
1022             LogError("Couldn't register on MMS received callback, err=" << err);
1023         }
1024
1025         m_dbusConnection->open(DBUS_BUS_SYSTEM);
1026     }
1027 }
1028
1029 bool Messaging::validateFilter(const Api::Tizen::FilterPtr& filter, const int funtionIndex){
1030         LogDebug("<<<");
1031
1032         bool retBool = false;
1033         LogDebug("funtionIndex = " << funtionIndex);    
1034
1035         if(filter != NULL){
1036                 if(funtionIndex == 0)
1037                 {
1038                         Platform::Messaging::StorageChangesMessageFilterValidatorPtr validatorMsg =
1039                                         Platform::Messaging::StorageChangesMessageFilterValidatorFactory::getStorageChangesMessageFilterValidator();
1040
1041                         FilterValidatorPtr filterValidatorMsg = DPL::StaticPointerCast<FilterValidator>(validatorMsg);
1042                         retBool = filter->validate(filterValidatorMsg);
1043                 }else if(funtionIndex == 1)
1044                 {
1045                         Platform::Messaging::StorageChangesConversationFilterValidatorPtr validatorConv =
1046                                         Platform::Messaging::StorageChangesConversationFilterValidatorFactory::getStorageChangesConversationFilterValidator();
1047
1048                         FilterValidatorPtr filterValidatorConv = DPL::StaticPointerCast<FilterValidator>(validatorConv);
1049                         retBool = filter->validate(filterValidatorConv);
1050                 }else if(funtionIndex == 2)
1051                 {
1052                         Platform::Messaging::StorageChangesFolderFilterValidatorPtr validatorFolder =
1053                                         Platform::Messaging::StorageChangesFolderFilterValidatorFactory::getStorageChangesFolderFilterValidator();
1054
1055                         FilterValidatorPtr filterValidatorFolder = DPL::StaticPointerCast<FilterValidator>(validatorFolder);
1056                         retBool = filter->validate(filterValidatorFolder);
1057                 }
1058                 
1059                 if(retBool == false){
1060                         Throw(WrtDeviceApis::Commons::InvalidArgumentException);
1061                 }
1062         }else{
1063                 LogDebug("filter is NULL");
1064                 retBool = false;
1065         }
1066
1067         LogDebug(">>> retBool:" << retBool);
1068         return retBool;
1069
1070 }
1071
1072
1073 void Messaging::removeOnMessageMsgReceived(Api::Messaging::EmitterMessageReceived::IdType id)
1074 {
1075     LogDebug("ENTER");
1076     m_onMessageReceived.detach(id);
1077     EmittersMessageReceived::LockType lock = m_onMessageReceived.getLock();
1078     if ((m_onMessageReceived.size()+m_onConversationReceived.size()+m_onFolderReceived.size()) == 0) {
1079         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(NULL);
1080         m_dbusConnection->close();
1081     }
1082 }
1083
1084 void Messaging::removeOnMessageConvReceived(Api::Messaging::EmitterConversationReceived::IdType id)
1085 {
1086     LogDebug("ENTER");
1087     m_onConversationReceived.detach(id);
1088     EmittersConversationReceived::LockType lock = m_onConversationReceived.getLock();
1089     if ((m_onMessageReceived.size()+m_onConversationReceived.size()+m_onFolderReceived.size()) == 0) {
1090         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(NULL);
1091         m_dbusConnection->close();
1092     }
1093 }
1094
1095 void Messaging::removeOnMessageFolderReceived(Api::Messaging::EmitterFolderReceived::IdType id)
1096 {
1097     LogDebug("ENTER");
1098     m_onFolderReceived.detach(id);
1099     EmittersFolderReceived::LockType lock = m_onFolderReceived.getLock();
1100     if ((m_onMessageReceived.size()+m_onConversationReceived.size()+m_onFolderReceived.size()) == 0) {
1101         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(NULL);
1102         m_dbusConnection->close();
1103     }
1104 }
1105
1106 void Messaging::OnEventReceived(const DBus::MessageEvent& event)
1107 {
1108     LogDebug("ENTER");
1109     EventMessageReceivedPtr jsEvent(new EventMessageReceived());
1110     DBus::MessagePtr message = event.GetArg0();
1111
1112
1113     if (!message) {
1114         jsEvent->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::PlatformException);
1115         m_onMessageReceived.emit(jsEvent);
1116     } else {
1117         if (message->getInterface() == DBUS_INTERFACE_EMAIL_RECEIVED) {
1118             int account_id = 0, mail_id = 0, thread_id = 0, status = 0;
1119             std::string name;
1120             emf_mailbox_t m_mailboxes;          
1121             emf_mailbox_t* mailboxes = NULL;
1122                         
1123             DBus::Message::ReadIterator it = message->getReadIterator();
1124             for (int i = 0; it->isValid(); it->next(), ++i) {
1125                 if ((i == 0) && (it->getArgType() == DBUS_TYPE_INT32)) {
1126                         status = it->getInt();
1127                                 LogInfo("status: " << status);                                  
1128                 } else if ((i == 1) && (it->getArgType() == DBUS_TYPE_INT32)) {
1129                     account_id = it->getInt();
1130                                         LogInfo("account_id: " << account_id);                                  
1131                 } else if ((i == 2) && (it->getArgType() == DBUS_TYPE_INT32)) {
1132                                         mail_id = it->getInt();
1133                                         LogInfo("mail_id: " << mail_id);                                                                                
1134                 } else if ((i == 3) && (it->getArgType() == DBUS_TYPE_STRING)) {
1135                                         name = it->getString();
1136                                         LogInfo("name: " << name);                                                                              
1137                      } else if ((i == 4) && (it->getArgType() == DBUS_TYPE_INT32)) {
1138                                         thread_id = it->getInt();
1139                                         LogInfo("thread_id: " << thread_id);                                                                            
1140                 }
1141             }
1142                                         
1143             if ((mail_id > 0) && (NOTI_MAIL_ADD == status)) 
1144             { // TODO also RECEIVE_THREAD_ITEM?
1145                 LogInfo("Email received. mail_id: " << mail_id);
1146
1147                 IMessagePtr msg = MessageFactory::createMessage(EMAIL, mail_id);
1148
1149                 // TODO Temporary fix: ignore messages from OUTBOX, SENTBOX & DRAFTBOX -> most probably we added them
1150                 Api::Messaging::FolderType folder = msg->getCurrentFolder();
1151                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1152                                 
1153                 if (OUTBOX != folder && SENTBOX != folder && DRAFTBOX !=
1154                     folder) {
1155                     IEmailPtr email = MessageFactory::convertToEmail(msg);
1156                     jsEvent->setMessage(msg);
1157                     if(m_onMessageReceived.size() > 0){
1158                     m_onMessageReceived.emit(jsEvent);
1159                     }
1160
1161                     if(m_onConversationReceived.size() > 0){
1162                     m_onConversationReceived.emit(jsEvent);
1163                     }
1164
1165                 } else {
1166                     LogWarning(
1167                         "New email message in ignored folder: " << folder);
1168                 }
1169             }
1170             else if ((mail_id > 0) && (NOTI_MAIL_DELETE == status)) 
1171             { // TODO also RECEIVE_THREAD_ITEM?
1172                 LogInfo("Email received. delete type: " << mail_id);                    
1173
1174                       std::vector<std::string> strIds = String::split(name, ',');
1175
1176                         std::stringstream stream;                                               
1177                         for (std::vector<std::string>::iterator it = strIds.begin(); it != strIds.end(); ++it) {
1178                             LogDebug("ID is :" << *it);
1179
1180                             if ( (*it).length() > 0 ) //vaild id
1181                             {
1182                                     stream<< *it;
1183                                     int id;
1184                                     stream >> id;
1185                                         
1186                                     IMessagePtr msg = MessageFactory::createMessage(EMAIL, id);
1187
1188                                 Api::Messaging::FolderType folder = msg->getCurrentFolder();
1189                                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_DELETED);
1190                                                 
1191                                 if (true) { // if (OUTBOX != folder && SENTBOX != folder && DRAFTBOX != folder)
1192                                     IEmailPtr email = MessageFactory::convertToEmail(msg);
1193                                     jsEvent->setMessage(msg);
1194                                     if(m_onMessageReceived.size() > 0){
1195                                             m_onMessageReceived.emit(jsEvent);
1196                                     }
1197                                     if(m_onConversationReceived.size() > 0){
1198                                         m_onConversationReceived.emit(jsEvent);
1199                                     }
1200                                 } else {
1201                                     LogWarning(
1202                                         "New email message in ignored folder: " << folder);
1203                                 }
1204                                 }
1205                                 
1206                             stream.clear();
1207                         } //for
1208                                         
1209             }
1210             else if ((mail_id > 0) && (NOTI_MAIL_UPDATE == status)) 
1211             { // TODO also RECEIVE_THREAD_ITEM?
1212                 LogInfo("Email received. mail_id: " << mail_id);
1213
1214                 IMessagePtr msg = MessageFactory::createMessage(EMAIL, mail_id);
1215
1216                 Api::Messaging::FolderType folder = msg->getCurrentFolder();
1217                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED);
1218                                 
1219                 if (true) { // if (OUTBOX != folder && SENTBOX != folder && DRAFTBOX != folder)
1220                     IEmailPtr email = MessageFactory::convertToEmail(msg);
1221                     jsEvent->setMessage(msg);
1222                     if(m_onMessageReceived.size() > 0)
1223                         m_onMessageReceived.emit(jsEvent);
1224                     if(m_onConversationReceived.size() > 0)
1225                     m_onConversationReceived.emit(jsEvent);
1226                 } else {
1227                     LogWarning(
1228                         "New email message in ignored folder: " << folder);
1229                 }
1230             }
1231             else if (NOTI_MAILBOX_ADD == status) 
1232             {
1233                 LogInfo("Emailbox received. account Id: " << account_id);
1234                 LogInfo("name Id: " << name);
1235                 email_get_mailbox_by_name(account_id, name.c_str(), &mailboxes);
1236
1237                 m_mailboxes = *mailboxes;
1238
1239                 Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes));
1240                 jsEvent->setMessageFolder(folderPtr);
1241                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1242                 if(m_onFolderReceived.size() > 0)
1243                 {               
1244                 m_onFolderReceived.emit(jsEvent);
1245                 }
1246
1247             }
1248             else if (NOTI_MAILBOX_UPDATE == status) 
1249             {
1250                 LogInfo("Emailbox received. account Id: " << account_id);
1251                 LogInfo("name Id: " << name);
1252                 email_get_mailbox_by_name(account_id, name.c_str(), &mailboxes);
1253
1254                 m_mailboxes = *mailboxes;
1255
1256                 Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes));
1257                 jsEvent->setMessageFolder(folderPtr);
1258                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED);
1259                                 
1260                 if(m_onFolderReceived.size() > 0)
1261                 {               
1262                 m_onFolderReceived.emit(jsEvent);
1263                 }
1264
1265
1266             }
1267             else if (NOTI_MAILBOX_DELETE == status) 
1268             {
1269                 LogInfo("Emailbox received. account Id: " << account_id);
1270                 LogInfo("name Id: " << name);
1271                 email_get_mailbox_by_name(account_id, name.c_str(), &mailboxes);
1272
1273                 m_mailboxes = *mailboxes;
1274
1275                 Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes));
1276                 jsEvent->setMessageFolder(folderPtr);
1277                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_DELETED);
1278                                 
1279                 if(m_onFolderReceived.size() > 0)
1280                 {               
1281                 m_onFolderReceived.emit(jsEvent);
1282                 }
1283
1284             }
1285             else 
1286             {
1287                 LogError("Couldn't retrieve message or it has been malformed.");
1288             }
1289         } else {
1290             LogDebug("Wrong DBus interface, skipping it.");
1291         }
1292     }
1293 }
1294
1295 void Messaging::onMessageStorageChanged(MSG_HANDLE_T handle,
1296         MSG_STORAGE_CHANGE_TYPE_T storageChangeType,
1297         MSG_MSGID_LIST_S *pMsgIdList,
1298         void* data)
1299 {
1300
1301     LogDebug("ENTER");
1302
1303         MSG_ERROR_T err = MSG_SUCCESS;
1304
1305         msg_message_t msg = msg_new_message();
1306         MSG_SENDINGOPT_S sendOpt = {0, };
1307
1308         err = msg_get_message(handle, *pMsgIdList->msgIdList, msg, &sendOpt);
1309
1310     LogDebug("err" << err);     
1311         
1312
1313         if (err != MSG_SUCCESS)
1314         {
1315                 LogDebug("Get Message Failed!");
1316                 msg_release_message(&msg);
1317                 return;
1318         }
1319         
1320     Messaging* this_ = static_cast<Messaging*>(data);
1321     if (this_) {
1322         Try {
1323                         int MsgType = msg_get_message_type(msg);
1324
1325             if((MsgType > MSG_TYPE_INVALID) && ( MsgType <= MSG_TYPE_SMS_REJECT))
1326             {
1327                 if(msg_get_message_type(msg) != MSG_TYPE_MMS_NOTI)
1328                         {
1329                     IMessagePtr message = MessageFactory::createMessage(
1330                                           SMS,
1331                                           msg_get_message_id(
1332                                           msg));
1333                     ISmsPtr sms = MessageFactory::convertToSms(message);
1334                     IConversationPtr conversation(new Conversation(message->getId(), SMS));
1335                     EventMessageReceivedPtr event(new EventMessageReceived());
1336                     event->setMessage(message);
1337                     event->setConversation(conversation);
1338
1339                     if(storageChangeType == MSG_STORAGE_CHANGE_INSERT)
1340                     {
1341                         event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1342                     }
1343                     else if(storageChangeType == MSG_STORAGE_CHANGE_UPDATE)
1344                     {
1345                         event->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED);
1346                     }
1347                     else if(storageChangeType == MSG_STORAGE_CHANGE_DELETE)
1348                     {
1349                         event->setMsg_Event_Type(EventMessageReceived::MSG_DELETED);
1350                     }
1351                     else if(storageChangeType == MSG_STORAGE_CHANGE_CONTACT)
1352                     {
1353                         event->setMsg_Event_Type(EventMessageReceived::MSG_MULTIPLE);
1354                     }
1355
1356                     if(this_->m_onMessageReceived.size() > 0){
1357                         this_->m_onMessageReceived.emit(event);
1358                     }
1359                     if(this_->m_onConversationReceived.size() > 0){
1360                     this_->m_onConversationReceived.emit(event);
1361                     }
1362                 }
1363                         else
1364                         {
1365                                 LogError("Ignore this sms, this is mms noti.");
1366                         }
1367             }
1368             else if((MsgType >= MSG_TYPE_MMS) && (MsgType <= MSG_TYPE_MMS_NOTI))
1369             {
1370                 if(msg_get_message_type(msg) != MSG_TYPE_MMS_NOTI)
1371                         {
1372                     IMessagePtr message = MessageFactory::createMessage(
1373                                           MMS,
1374                                           msg_get_message_id(
1375                                           msg));
1376                                         IMmsPtr mms = MessageFactory::convertToMms(message);
1377                     IConversationPtr conversation(new Conversation(message->getId(), MMS));
1378                                         EventMessageReceivedPtr event(new EventMessageReceived());
1379                                         event->setMessage(message);
1380                     event->setConversation(conversation);
1381
1382                     if(storageChangeType == MSG_STORAGE_CHANGE_INSERT)
1383                     {
1384                         event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1385                     }
1386                     else if(storageChangeType == MSG_STORAGE_CHANGE_UPDATE)
1387                     {
1388                         event->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED);
1389                     }
1390                     else if(storageChangeType == MSG_STORAGE_CHANGE_DELETE)
1391                     {
1392                         event->setMsg_Event_Type(EventMessageReceived::MSG_DELETED);
1393                     }
1394                     else if(storageChangeType == MSG_STORAGE_CHANGE_CONTACT)
1395                     {
1396                        event->setMsg_Event_Type(EventMessageReceived::MSG_MULTIPLE);
1397                     }
1398                     if(this_->m_onMessageReceived.size() > 0){
1399                         this_->m_onMessageReceived.emit(event);
1400                     }
1401                     if(this_->m_onConversationReceived.size() > 0){
1402                         this_->m_onConversationReceived.emit(event);
1403                     }
1404                 }
1405                 else
1406                 {
1407                                 LogError("Ignore this mms, this is mms noti.");
1408                 }
1409
1410             }
1411         }
1412         Catch(WrtDeviceApis::Commons::ConversionException) {
1413             LogError("Couldn't convert message to sms.");
1414         }
1415     }
1416 }
1417
1418
1419 void Messaging::onSmsReceived(MSG_HANDLE_T handle,
1420         msg_message_t msg,
1421         void* data)
1422 {
1423     LogDebug("ENTER");
1424     Messaging* this_ = static_cast<Messaging*>(data);
1425     if (this_) {
1426         Try {
1427                         if(msg_get_message_type(msg) != MSG_TYPE_MMS_NOTI)
1428                         {
1429             IMessagePtr message = MessageFactory::createMessage(
1430                     SMS,
1431                     msg_get_message_id(
1432                         msg));
1433             ISmsPtr sms = MessageFactory::convertToSms(message);
1434             IConversationPtr conversation(new Conversation(message->getId(), SMS));
1435                         
1436             EventMessageReceivedPtr event(new EventMessageReceived());
1437             event->setMessage(message);
1438             event->setConversation(conversation);
1439                         event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1440                         this_->m_onMessageReceived.emit(event);
1441         }
1442                         else
1443                         {
1444                                 LogError("Ignore this sms, this is mms noti.");
1445                         }
1446         }
1447         Catch(WrtDeviceApis::Commons::ConversionException) {
1448             LogError("Couldn't convert message to sms.");
1449         }
1450     }
1451 }
1452
1453 void Messaging::onMmsReceived(MSG_HANDLE_T handle,
1454         msg_message_t msg,
1455         void* data)
1456 {
1457     LogDebug("ENTER");
1458     Messaging* this_ = static_cast<Messaging*>(data);
1459     if (this_) {
1460         Try {
1461             IMessagePtr message = MessageFactory::createMessage(
1462                     MMS,
1463                     msg_get_message_id(
1464                         msg));
1465             IMmsPtr mms = MessageFactory::convertToMms(message);
1466             IConversationPtr conversation(new Conversation(message->getId(), MMS));
1467             EventMessageReceivedPtr event(new EventMessageReceived());
1468             event->setMessage(message);
1469             event->setConversation(conversation);
1470                         event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1471                         this_->m_onMessageReceived.emit(event);
1472         }
1473         Catch(WrtDeviceApis::Commons::ConversionException) {
1474             LogError("Couldn't convert message to mms.");
1475         }
1476     }
1477 }
1478
1479 void Messaging::getNumberOfEmails(Api::Messaging::FolderType folder,
1480         int* read,
1481         int* unread)
1482 {
1483     LOG_ENTER
1484
1485     emf_mailbox_t mailbox = {};
1486     mailbox.account_id = 0; // means for all accounts
1487     mailbox.name = String::strdup(
1488             EmailConverter::toMailboxName(folder)
1489             );
1490
1491     int error = email_count_message(&mailbox, read, unread);
1492     free(mailbox.name);
1493
1494     if (EMF_ERROR_NONE != error) {
1495         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1496                  "Couldn't get number of emails. [" << error << "]");
1497     }
1498
1499     LOG_EXIT
1500 }
1501
1502 void Messaging::getNumberOfSms(Api::Messaging::FolderType folder,
1503         int* read,
1504         int* unread)
1505 {
1506     getNumberOfSmsMms(folder, read, unread, SMS);
1507 }
1508
1509 void Messaging::getNumberOfMms(Api::Messaging::FolderType folder,
1510         int* read,
1511         int* unread)
1512 {
1513     getNumberOfSmsMms(folder, read, unread, MMS);
1514 }
1515
1516 void Messaging::getNumberOfSmsMms(Api::Messaging::FolderType folder,
1517         int* read,
1518         int* unread,
1519         Api::Messaging::MessageType msgType)
1520 {
1521     MSG_LIST_S folderListView = { 0, NULL };
1522
1523     *read = 0;
1524     *unread = 0;
1525
1526     Try
1527     {
1528         MSG_MESSAGE_TYPE_T msgTypePlatform;
1529         if (SMS == msgType) {
1530             msgTypePlatform = MSG_TYPE_SMS;
1531         } else if (MMS == msgType) {
1532             msgTypePlatform = MSG_TYPE_MMS;
1533         } else {
1534             LogError("no supported message type in this method");
1535             Throw(WrtDeviceApis::Commons::PlatformException);
1536         }
1537
1538         MSG_FOLDER_ID_T msgFolderId;
1539         switch (folder) {
1540         case INBOX:
1541             msgFolderId = MSG_INBOX_ID;
1542             break;
1543         case OUTBOX:
1544             msgFolderId = MSG_OUTBOX_ID;
1545             break;
1546         case SPAMBOX:
1547             msgFolderId = MSG_SPAMBOX_ID;
1548             break;
1549         case SENTBOX:
1550             msgFolderId = MSG_SENTBOX_ID;
1551             break;
1552         case DRAFTBOX:
1553             msgFolderId = MSG_DRAFT_ID;
1554             break;
1555         default:
1556             LogError("wrong folder type");
1557             Throw(WrtDeviceApis::Commons::PlatformException);
1558             break;
1559         }
1560
1561         const MSG_SORT_RULE_S sort_rules = { MSG_SORT_BY_DISPLAY_TIME, true };
1562         if (msg_get_folder_view_list(MsgGetCommonHandle(), msgFolderId,
1563                                      &sort_rules,
1564                                      &folderListView) != MSG_SUCCESS) {
1565             LogDebug(
1566                 "msg_get_folder_view_list empty or failed, msgFolderId=" <<
1567                 (int) msgFolderId);
1568             Throw(WrtDeviceApis::Commons::PlatformException);
1569         }
1570         // go thtough all message to check type of message
1571         LogDebug("msgCount=" << (int) folderListView.nCount);
1572         for (int msg_cnt = 0; msg_cnt < folderListView.nCount; msg_cnt++) {
1573             LogDebug("msgMainType=" <<
1574                                          (int) msg_get_message_type(folderListView.
1575                                                                         msgInfo[
1576                                                                 msg_cnt]) <<
1577                      ", searching for = " << (int) msgTypePlatform);
1578             if (msgTypePlatform ==
1579                                 msg_get_message_type(folderListView.msgInfo[
1580                                                      msg_cnt])) {
1581                 if (msg_is_read(folderListView.msgInfo[msg_cnt]))
1582                 {
1583                     (*read)++;
1584                 } else {
1585                     (*unread)++;
1586                 }
1587             }
1588         }
1589                 msg_release_message_list(&folderListView);
1590
1591         LogDebug("readed=" << *read << ", unReaded=" << *unread);
1592     }
1593
1594     Catch(WrtDeviceApis::Commons::PlatformException) {
1595         if (folderListView.nCount) {
1596                         msg_release_message_list(&folderListView);
1597         }
1598         throw;
1599     }
1600 }
1601
1602         vector<Api::Messaging::IMessagePtr> Messaging::findSms(Api::Messaging::FolderType folder, const Api::Tizen::FilterPtr& filter)
1603         {
1604                 LogDebug("<<<");
1605
1606                 vector<Api::Messaging::IMessagePtr> retVal;
1607                 msg_message_t msg = msg_new_message();
1608                 MSG_LIST_S folder_list_view = {0, NULL};
1609
1610                 Try{
1611                         const MSG_SORT_RULE_S sort_rules = {MSG_SORT_BY_DISPLAY_TIME, true};
1612                         MSG_ERROR_T res = MSG_ERR_UNKNOWN;
1613                         const MSG_FOLDER_ID_T platformFolder = convertFolderToPlatform(folder);
1614                         res = msg_get_folder_view_list(MsgGetCommonHandle(), platformFolder, &sort_rules, &folder_list_view);
1615
1616                         if (MSG_SUCCESS != res) {
1617                                 LogError("msg_get_folder_view_list failed " << res);
1618                                 Throw(WrtDeviceApis::Commons::PlatformException);
1619                         }
1620
1621                         for (int i = 0; i < folder_list_view.nCount; i++) {
1622                                 if (MSG_TYPE_SMS == msg_get_message_type(folder_list_view.msgInfo[i])) {
1623                                         int l_msgId = msg_get_message_id(folder_list_view.msgInfo[i]);
1624                                         Api::Messaging::IMessagePtr msg = MessageFactory::createMessage(SMS, l_msgId);
1625
1626                                         //                if (!filter || !filter->isValid() ||
1627                                         //                    filter->compare(MessageFactory::convertToSms(msg))) {
1628                                                             retVal.push_back(msg);
1629                                         //                }
1630                                 }
1631                         }
1632
1633                         msg_release_message_list(&folder_list_view);
1634                 }Catch(WrtDeviceApis::Commons::PlatformException) {
1635                         LogError("Problem with message creation, cleaning");
1636                         if (folder_list_view.nCount) {
1637                                 msg_release_message_list(&folder_list_view);
1638                         }
1639                         if (msg) {
1640                                 msg_release_message(&msg);
1641                         }
1642                         throw;
1643                 }
1644
1645                 LogDebug(">>>");
1646                 return retVal;
1647         }
1648
1649         vector<Api::Messaging::IMessagePtr> Messaging::findMms(Api::Messaging::FolderType folder,
1650                         const Api::Tizen::FilterPtr& filter)
1651         {
1652                 vector<Api::Messaging::IMessagePtr> retVal;
1653                 msg_message_t msg = msg_new_message();
1654                 MSG_LIST_S folder_list_view = {0, NULL};
1655
1656                 Try
1657                 {
1658                         const MSG_SORT_RULE_S sort_rules = {MSG_SORT_BY_DISPLAY_TIME, true};
1659                         MSG_ERROR_T res = MSG_ERR_UNKNOWN;
1660                         const MSG_FOLDER_ID_T platformFolder = convertFolderToPlatform(folder);
1661                         res = msg_get_folder_view_list(
1662                                         MsgGetCommonHandle(), platformFolder, &sort_rules,
1663                                         &folder_list_view);
1664
1665                         if (MSG_SUCCESS != res) {
1666                                 LogError("msg_Get_folder_view_list failed" << res);
1667                                 Throw(WrtDeviceApis::Commons::PlatformException);
1668                         }
1669
1670                         for (int i = 0; i < folder_list_view.nCount; i++) {
1671                                 if (MSG_TYPE_MMS ==
1672                                                 msg_get_message_type(folder_list_view.
1673                                                                 msgInfo[i])) {
1674                                         int l_msgId = msg_get_message_id(
1675                                                         folder_list_view.msgInfo[i]);
1676                                         Api::Messaging::IMessagePtr msg = MessageFactory::createMessage(MMS, l_msgId);
1677                                 }
1678                         }
1679
1680                         msg_release_message_list(&folder_list_view);
1681                 }
1682
1683                 Catch(WrtDeviceApis::Commons::PlatformException) {
1684                         LogError("Problem with message creation, cleaning");
1685                         if (folder_list_view.nCount) {
1686                                 msg_release_message_list(&folder_list_view);
1687                         }
1688                         if (msg) {
1689                                 msg_release_message(&msg);
1690                         }
1691                         throw;
1692                 }
1693
1694                 return retVal;
1695         }
1696
1697 void Messaging::createFolder(MessageType msgType,
1698         const string& userFolder)
1699 {
1700     switch (msgType) {
1701     case Api::Messaging::SMS:
1702     case Api::Messaging::MMS:
1703         createMsgServiceFolder(userFolder);
1704         break;
1705     case Api::Messaging::EMAIL:
1706         createEmailFolder(userFolder);
1707         break;
1708     default:
1709         LogError("msg not supported");
1710         Throw(WrtDeviceApis::Commons::UnknownException);
1711     }
1712 }
1713
1714 void Messaging::createMsgServiceFolder(const std::string& userFolder)
1715 {
1716     if (userFolder.length() > MAX_FOLDER_NAME_SIZE) {
1717         LogError("folder name to long");
1718         Throw(WrtDeviceApis::Commons::PlatformException);
1719     }
1720
1721     MSG_FOLDER_INFO_S folderInfo;
1722
1723     folderInfo.folderId = 0;
1724     strncpy(folderInfo.folderName, userFolder.c_str(), userFolder.length());
1725
1726     folderInfo.folderType = MSG_FOLDER_TYPE_USER_DEF;
1727
1728     if (msg_add_folder(MsgGetCommonHandle(), &folderInfo) != MSG_SUCCESS) {
1729         LogError("msg_add_folder failed");
1730         Throw(WrtDeviceApis::Commons::PlatformException);
1731     }
1732 }
1733
1734 void Messaging::createEmailFolder(const std::string& userFolder)
1735 {
1736     //TODO
1737     LogError("TODO");
1738     Throw(WrtDeviceApis::Commons::UnknownException);
1739 }
1740
1741 void Messaging::deleteFolder(MessageType msgType,
1742         const string& userFolder)
1743 {
1744     switch (msgType) {
1745     case Api::Messaging::SMS:
1746     case Api::Messaging::MMS:
1747         deleteMsgServiceFolder(userFolder);
1748         break;
1749     case Api::Messaging::EMAIL:
1750         deleteEmailFolder(userFolder);
1751         break;
1752     default:
1753         LogError("msg not supported");
1754         Throw(WrtDeviceApis::Commons::UnknownException);
1755     }
1756 }
1757
1758 void Messaging::deleteMsgServiceFolder(const string& userFolder)
1759 {
1760     Try
1761     {
1762         int platformFolderId = convertFolderToPlatform(userFolder);
1763         if (MSG_SUCCESS !=
1764             msg_delete_folder(MsgGetCommonHandle(), platformFolderId)) {
1765             LogError("msg_get_folder_list failed");
1766             Throw(WrtDeviceApis::Commons::PlatformException);
1767         }
1768     }
1769     Catch(WrtDeviceApis::Commons::PlatformException) {
1770         throw;
1771     }
1772 }
1773
1774 void Messaging::deleteEmailFolder(const string& userFolder)
1775 {
1776     //TODO
1777     LogError("TODO");
1778     Throw(WrtDeviceApis::Commons::UnknownException);
1779 }
1780
1781 vector<string> Messaging::getFolderNames(MessageType msgType)
1782 {
1783     switch (msgType) {
1784     case Api::Messaging::SMS:
1785     case Api::Messaging::MMS:
1786         return getFolderNamesMsgService();
1787     case Api::Messaging::EMAIL:
1788         return getFolderNamesEmail();
1789     default:
1790         LogError("msg not supported");
1791         Throw(WrtDeviceApis::Commons::UnknownException);
1792     }
1793 }
1794
1795 vector<string> Messaging::getFolderNamesMsgService()
1796 {
1797     vector<string> retVal;
1798     MSG_FOLDER_LIST_S msgFolderList = { 0, NULL }; // output data
1799
1800     Try
1801     {
1802         if (msg_get_folder_list(MsgGetCommonHandle(),
1803                                 &msgFolderList) != MSG_SUCCESS) {
1804             LogError("msg_get_folder_list failed");
1805             Throw(WrtDeviceApis::Commons::PlatformException);
1806         }
1807
1808         LogDebug("number of folder=" << msgFolderList.nCount);
1809         for (int i = 0; i < msgFolderList.nCount; i++) {
1810             LogDebug("folderName=" << msgFolderList.folderInfo[i].folderName);
1811             LogDebug("folderId=" << (int) msgFolderList.folderInfo[i].folderId);
1812             LogDebug(
1813                 "folderType=" <<
1814                 (int) msgFolderList.folderInfo[i].folderType);
1815             retVal.push_back(msgFolderList.folderInfo[i].folderName);
1816         }
1817         (void) msg_release_folder_list(&msgFolderList);
1818     }
1819
1820     Catch(WrtDeviceApis::Commons::PlatformException) {
1821         if (msgFolderList.nCount) {
1822             (void) msg_release_folder_list(&msgFolderList);
1823         }
1824         throw;
1825     }
1826     return retVal;
1827 }
1828
1829 vector<string> Messaging::getFolderNamesEmail()
1830 {
1831     vector<string> retVal;
1832
1833     string tmpStr;
1834     emf_mailbox_t* mailboxes = NULL;
1835     int mailboxesCount;
1836     string emailAccountName;
1837     Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount();
1838
1839     Try
1840     {
1841         if (!email_get_mailbox_list(account.getIntId(), -1, &mailboxes,
1842                                     &mailboxesCount) || !mailboxes) {
1843             LogError("error during get mailboxes");
1844         }
1845         for (int i = 0; i < mailboxesCount; i++) {
1846             retVal.push_back(mailboxes->name);
1847             LogDebug("mailbox found, name=" << mailboxes->name);
1848             mailboxes++;
1849         }
1850     }
1851
1852     Catch(WrtDeviceApis::Commons::PlatformException) {
1853         // nothing to clean, re-throw exception
1854         throw;
1855     }
1856
1857     return retVal;
1858 }
1859
1860 vector<Api::Messaging::IMessagePtr> Messaging::findEmail(const std::string &folder,
1861                 const Api::Tizen::FilterPtr& filter)
1862 {
1863     vector<Api::Messaging::IMessagePtr> retVal;
1864
1865     Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount();
1866     if (account.getId().empty()) {
1867         LogWarning("No valid email accounts. Skipping");
1868         return retVal;
1869     }
1870
1871     int accountId = account.getIntId();
1872
1873     // number of found emails
1874     int count = 0;
1875     // start index
1876     int startIndex = 0;
1877
1878     do {
1879         emf_mail_list_item_t* results = NULL;
1880         int err = email_get_mail_list_ex(accountId,
1881                                          folder.c_str(),
1882                                          EMF_LIST_TYPE_NORMAL,
1883                                          startIndex,
1884                                          MESSAGE_FIND_LIMIT,
1885                                          EMF_SORT_DATETIME_HIGH,
1886                                          &results,
1887                                          &count);
1888         DPL::ScopedFree<emf_mail_list_item_t> autoFree(results);
1889         (void)autoFree;
1890         if (EMF_ERROR_MAIL_NOT_FOUND == err || results == NULL) {
1891             LogWarning("No emails found in mailbox: " << folder);
1892             break;
1893         } else if (EMF_ERROR_NONE != err) {
1894             LogError(
1895                 "Unable to get mail list for mailbox: " << folder <<
1896                 ", Error: " << err);
1897             Throw(WrtDeviceApis::Commons::PlatformException);
1898         }
1899
1900         // apply filter
1901         for (int i = 0; i < count; ++i) {
1902             Api::Messaging::IMessagePtr msg = MessageFactory::createMessage(EMAIL, results[i].mail_id);
1903
1904
1905             if (!filter
1906 //                      || filter->compare(MessageFactory::convertToEmail(msg))         //TODO implemnet compare in filter
1907                         ) {
1908                 retVal.push_back(msg);
1909             }
1910         }
1911
1912         startIndex += count;
1913     }
1914     while (count >= MESSAGE_FIND_LIMIT);
1915
1916     return retVal;
1917 }
1918
1919 vector<Api::Messaging::IMessagePtr> Messaging::findEmail(Api::Messaging::FolderType folder,
1920                 const Api::Tizen::FilterPtr& filter)
1921 {
1922     vector<Api::Messaging::IMessagePtr> result;
1923
1924     Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount();
1925     if (account.getId().empty()) {
1926         LogWarning("No valid email accounts.");
1927         return result;
1928     }
1929
1930     string name;
1931     try {
1932         name = EmailConverter::toMailboxName(folder);
1933     }
1934     catch (const WrtDeviceApis::Commons::PlatformException& ex) {
1935         LogWarning(ex.DumpToString());
1936         return result;
1937     }
1938
1939     int accountId = account.getIntId();
1940     int startIndex = 0;
1941     int count = 0;
1942     do {
1943         emf_mail_list_item_t* messages = NULL;
1944         int error = email_get_mail_list_ex(accountId,
1945                                            name.c_str(),
1946                                            EMF_LIST_TYPE_NORMAL,
1947                                            startIndex,
1948                                            MESSAGE_FIND_LIMIT,
1949                                            EMF_SORT_DATETIME_HIGH,
1950                                            &messages,
1951                                            &count);
1952         DPL::ScopedFree<emf_mail_list_item_t> freeGuard(messages);
1953         if ((EMF_ERROR_MAIL_NOT_FOUND == error) || (NULL == messages)) {
1954             LogWarning("No emails found in mailbox: " << name);
1955             break;
1956         } else if (EMF_ERROR_NONE != error) {
1957             ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1958                      "Couldn't get mail list from mailbox: " << name <<
1959                      ". [" << error << "]");
1960         }
1961
1962         for (int i = 0; i < count; ++i) {
1963             Api::Messaging::IMessagePtr msg =
1964                 MessageFactory::createMessage(EMAIL, messages[i].mail_id);
1965             if (!filter
1966 //                      ||filter->compare(MessageFactory::convertToEmail(msg))          //TODO implement compare in filter 
1967                 ) {
1968                 result.push_back(msg);
1969             }
1970         }
1971
1972         startIndex += count;
1973     }
1974     while (count >= MESSAGE_FIND_LIMIT);
1975
1976     return result;
1977 }
1978
1979 int Messaging::getConversationId(const int& msgId, const MessageType& msgtype)
1980 {
1981         LogDebug("Enter");
1982         
1983         switch(msgtype)
1984         {
1985                 case EMAIL:
1986                 {
1987                         int index = 0, count = 0;
1988                         char *mailBox = NULL;
1989                         emf_mail_list_item_t *mailList = NULL;
1990                         
1991                         LogDebug("Current Account " << m_currentEmailAccountId);
1992
1993                         try 
1994                         {
1995                                 if (email_get_mailbox_name_by_mail_id(msgId, &mailBox) != EMF_ERROR_NONE)
1996                                 {
1997                                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "get mail box fail" );
1998                                 }
1999
2000                                 if (email_get_mail_list_ex(m_currentEmailAccountId, mailBox, EMF_LIST_TYPE_NORMAL, 0, MESSAGE_FIND_LIMIT, 
2001                                         EMF_SORT_DATETIME_HIGH, &mailList, &count) != EMF_ERROR_NONE)
2002                                 {
2003                                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "get email list fail" );
2004                                 }
2005
2006                                 if (mailBox)
2007                                         free(mailBox);
2008                                 
2009                                 for (index = 0; index < count; index++)
2010                                 {
2011                                         if (mailList[index].mail_id == (int)msgId)
2012                                         {
2013                                                 return mailList[index].thread_id;
2014                                         }
2015                                 }
2016                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException, "can not find msg" );
2017                         }
2018                         catch (const WrtDeviceApis::Commons::Exception& ex) 
2019                         {
2020                                 if (mailBox)
2021                                         free(mailBox);
2022                                 
2023                                 LogError("Exception: " << ex.GetMessage());
2024                                 throw;  
2025                         }
2026                         return MSG_ERR_INVALID_MSG_TYPE;
2027                 }
2028                 break;
2029                 case SMS:
2030                 case MMS:
2031                 {
2032                         msg_message_t msg = msg_new_message();
2033                         MSG_SENDINGOPT_S sendOpt = {0, };
2034                         MSG_HANDLE_T handle = MsgGetCommonHandle();
2035                         MSG_ERROR_T err = MSG_SUCCESS;
2036
2037                         err = msg_get_message(handle, msgId, msg, &sendOpt);
2038
2039
2040                         if( err < MSG_SUCCESS )
2041                         {
2042                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException,
2043                                 "can not find msg id(" << msgId << ")");
2044                         }
2045
2046                         err = msg_get_ith_thread_id(msg, 0);
2047                         LogDebug(err);
2048                         if( err < MSG_SUCCESS )
2049                         {
2050                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException,
2051                                 "can not find thread with msg id(" << msgId << ")");
2052                         }
2053
2054                         return err;
2055                 }
2056                 break;
2057                 default:
2058                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
2059                                 "Wrong Type (" << msgId << ")");
2060                         return MSG_ERR_INVALID_MSG_TYPE;
2061                 
2062         }
2063 }
2064
2065 std::vector<Api::Messaging::IConversationPtr> Messaging::queryConversations(const Api::Tizen::SortModePtr& sortMode,
2066                 const Api::Tizen::FilterPtr& filter, long limit, long offset)
2067 {
2068         LogDebug("Enter");
2069
2070         std::vector<Api::Messaging::IConversationPtr> result;
2071         std::string filterSql;
2072
2073         ConversationQueryGeneratorPtr queryGenerator(new ConversationQueryGenerator(sortMode, limit, offset));
2074         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
2075         filter->travel(filterVisitor, 0);
2076
2077         LogDebug("filterSql:[" << filterSql <<"]");
2078
2079         int conversationType = queryGenerator->getMessageType();
2080         switch(conversationType){
2081                 case Api::Messaging::EMAIL:{
2082                         LogDebug("type is EMAIL:[" << conversationType <<"]");
2083                         queryGenerator->reset(MessageQueryGenerator::MODE_EMAIL);
2084                         filter->travel(filterVisitor, 0);
2085                         filterSql = queryGenerator->getQuery();
2086                         result = queryEmailConversation(filterSql);
2087                         break;
2088                 }
2089
2090                 case Api::Messaging::SMS:{
2091                         LogDebug("type is SMS:[" << conversationType <<"]");
2092                         queryGenerator->reset(MessageQueryGenerator::MODE_SMS_MMS);
2093                         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
2094                         filter->travel(filterVisitor, 0);
2095                         filterSql = queryGenerator->getQuery();
2096                         result = querySmsMmsConversation(filterSql);
2097                         break;
2098                 }
2099
2100                 case Api::Messaging::MMS:{
2101                         LogDebug("type is MMS:[" << conversationType <<"]");
2102                         result = querySmsMmsConversation(filterSql);
2103                         break;
2104                 }
2105
2106                 default:{
2107                         LogError("[ERROR] >>> invlid type:[" << conversationType <<"]");
2108                  return result;
2109                 }
2110         }       //switch
2111
2112         return result;
2113 }
2114
2115 bool Messaging::deleteConversations(const Api::Tizen::SortModePtr& sortMode, const Api::Tizen::FilterPtr& filter)
2116 {
2117         LogDebug("Enter");
2118
2119         std::vector<Api::Messaging::IConversationPtr> conversationsToDelete = queryConversations(sortMode, filter);
2120         return deleteConversations(conversationsToDelete);
2121 }
2122
2123 bool Messaging::deleteConversations(const std::vector<Api::Messaging::IConversationPtr>& conversations)
2124 {
2125         LogDebug("Enter");
2126
2127         if (conversations.size() == 0)
2128                 return false;
2129         
2130         if (conversations[0]->getType() == Api::Messaging::EMAIL)
2131         {
2132                 LogDebug("Enter-Email");
2133                 int threadId = 0;
2134
2135                 for (std::size_t i = 0; i < conversations.size(); ++i) 
2136                 {
2137                         threadId = conversations[i]->getId();
2138                         
2139                         if (email_delete_thread(threadId, false) != EMF_ERROR_NONE)
2140                         {
2141                                 return false;
2142                         }
2143                 }
2144         }
2145         else
2146         {
2147                 LogDebug("Enter-Msg");
2148                 MSG_THREAD_ID_T threadId = 0;
2149                 MSG_HANDLE_T handle = MsgGetCommonHandle();
2150                 
2151                 for (std::size_t i = 0; i < conversations.size(); ++i) 
2152                 {
2153                         threadId = conversations[i]->getId();
2154                         if (msg_delete_thread_message_list(handle, threadId) != MSG_SUCCESS)
2155                         {
2156                                 return false;
2157                         }
2158                 }
2159         }
2160         return true;
2161 }
2162
2163 std::vector<Api::Messaging::IMessageFolderPtr> Messaging::queryFolders(const Api::Tizen::FilterPtr& filter)
2164 {
2165         LogDebug("Enter");
2166
2167         emf_mailbox_t* mailboxes = NULL;
2168         emf_mailbox_t m_mailboxes;
2169         int mailboxesCount;
2170
2171         std::vector<Api::Messaging::IMessageFolderPtr> result;
2172         std::string folderName;
2173         int accountId = 0;
2174
2175     Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount();
2176         
2177         if (account.getId().empty()) {
2178                 LogWarning("No valid email accounts. Skipping");
2179                 return result;
2180         }
2181
2182         const vector<Api::Messaging::EmailAccountInfo> accounts = getEmailAccounts();
2183
2184         FolderQueryGeneratorPtr queryGenerator(new FolderQueryGenerator());
2185         
2186         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
2187         queryGenerator->reset();
2188         filter->travel(filterVisitor, 0);
2189         accountId = queryGenerator->getAccountId();
2190
2191         if(accountId == 0)
2192         {
2193                 LogWarning("No valid email accounts. accountId : 0");
2194                 return result;  
2195         }
2196
2197         if(queryGenerator->isFolderPathExist() == 1){
2198                         folderName = queryGenerator->getFolderPath();
2199         
2200                 if(email_get_mailbox_by_name(accountId, folderName.c_str(), &mailboxes) != 1)
2201                 {
2202                         LogError("error during get mailboxes");         
2203                         return result;                          
2204                 }
2205
2206                 m_mailboxes = *mailboxes;                       
2207                 Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes));
2208                 result.push_back(folderPtr);
2209                         
2210         }else{
2211         if (!email_get_mailbox_list(accountId, -1, &mailboxes, &mailboxesCount) || !mailboxes) 
2212         {
2213                 LogError("error during get mailboxes");         
2214                 return result;          
2215         }
2216
2217         if (mailboxesCount <= 0)
2218         {
2219                 LogDebug("Empty...");
2220         }
2221         else 
2222         {
2223                 for (int i = 0; i < mailboxesCount; i++)
2224                 {
2225         
2226                         m_mailboxes = *mailboxes;                       
2227                         Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes));
2228                         result.push_back(folderPtr);
2229                         mailboxes++;                    
2230                 }
2231         }
2232         }
2233         return result;
2234
2235 }
2236
2237 }
2238 }
2239 }