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