9edf4113fa027eaee32e05ad45111a47c35115ec
[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     email_account_t* accounts = NULL;
859     int count = 0;
860     Try {
861         if (!email_get_account_list(&accounts, &count)) {
862             ThrowMsg(WrtDeviceApis::Commons::PlatformException,
863                      "Couldn't get e-mail accounts.");
864         }
865
866         if (0 == count) {
867             ThrowMsg(WrtDeviceApis::Commons::PlatformException, "No e-mail account found.");
868         }
869
870         vector<Api::Messaging::EmailAccountInfo> result;
871         for (int i = 0; i < count; ++i) {
872             Api::Messaging::EmailAccountInfo account(accounts[i].account_id,
873                                           accounts[i].incoming_server_user_name,
874                                           accounts[i].user_email_address);
875             result.push_back(account);
876         }
877
878         if (accounts != NULL) {
879             email_free_account(&accounts, count);
880         }
881
882         return result;
883     }
884     Catch(WrtDeviceApis::Commons::PlatformException) {
885         if (accounts != NULL) {
886             email_free_account(&accounts, count);
887         }
888         throw;
889     }
890 }
891
892 int Messaging::getEmailAccountId(const std::string& account)
893 {
894     int retVal = 0;
895     string tmpAccount = account;
896     email_account_t *pAccountArray = NULL;
897     int iCount = 0;
898
899     Try
900     {
901         if (account.empty()) {
902             tmpAccount = getCurrentEmailAccount().getAddress();
903             if (tmpAccount.empty()) {
904                 LogError(
905                     "current email account is not set, possible that no account created");
906                 Throw(WrtDeviceApis::Commons::PlatformException);
907             }
908         }
909
910         if (!email_get_account_list(&pAccountArray, &iCount)) {
911             LogError("email_get_account_list error");
912             Throw(WrtDeviceApis::Commons::PlatformException);
913         }
914
915         if (0 == iCount) {
916             LogError("no email account exist");
917             Throw(WrtDeviceApis::Commons::PlatformException);
918         }
919
920         for (int i = 0; i < iCount; i++) {
921             string tmp = pAccountArray[i].user_email_address;
922             if (tmp == tmpAccount) {
923                 m_currentEmailAccountId = pAccountArray[i].account_id;
924                 retVal = m_currentEmailAccountId;
925                 break;
926             }
927         }
928
929         if (0 == m_currentEmailAccountId) {
930             LogError("wrong email account ID");
931             Throw(WrtDeviceApis::Commons::PlatformException);
932         }
933
934         if (pAccountArray != NULL) {
935             LogDebug("free account, ptr=" << pAccountArray);
936             email_free_account(&pAccountArray, iCount);
937         }
938
939         if (0 == retVal) {
940             LogError("no email account created");
941             Throw(WrtDeviceApis::Commons::PlatformException);
942         }
943     }
944
945     Catch(WrtDeviceApis::Commons::PlatformException) {
946         LogError("exception catch, platform exception");
947         if (pAccountArray != NULL) {
948             email_free_account(&pAccountArray, iCount);
949         }
950         throw;
951     }
952
953     return retVal;
954 }
955
956 void Messaging::fetchEmailHeaders()
957 {
958     email_mailbox_t *mailbox = NULL;
959     unsigned handle = 0;
960     mailbox = static_cast<email_mailbox_t*>(calloc(sizeof (email_mailbox_t), 1));
961     if (!mailbox) {
962         LogError("calloc failed");
963         return;
964     }
965     mailbox->account_id = m_currentEmailAccountId;
966     mailbox->mailbox_name = strdup(EMAIL_INBOX_NAME);
967 //    if (EMAIL_ERROR_NONE != email_sync_header(mailbox, &handle)) {
968     if (EMAIL_ERROR_NONE != email_sync_header(mailbox->account_id, 0, &handle)) {
969         LogError("email_sync_header failed");
970     }
971     email_free_mailbox(&mailbox, 1);
972 }
973
974 int Messaging::convertFolderToPlatform(const FolderType folder)
975 {
976     msg_folder_id_t platfromFolderId;
977     switch (folder) {
978     case INBOX:
979         platfromFolderId = MSG_INBOX_ID;
980         break;
981     case DRAFTBOX:
982         platfromFolderId = MSG_DRAFT_ID;
983         break;
984     case OUTBOX:
985         platfromFolderId = MSG_OUTBOX_ID;
986         break;
987     case SENTBOX:
988         platfromFolderId = MSG_SENTBOX_ID;
989         break;
990     case SPAMBOX:
991     // intentionally not break in platform is no spambox
992     default:
993         LogError("Invalid folder: " << folder);
994         Throw(WrtDeviceApis::Commons::PlatformException);
995     }
996
997     return platfromFolderId;
998 }
999
1000 int Messaging::convertFolderToPlatform(const std::string &folder)
1001 {
1002 //    MSG_FOLDER_LIST_S folderList = { 0, NULL };
1003
1004     int result = 0;
1005 /*      
1006     Try
1007     {
1008         if (MSG_SUCCESS !=
1009             msg_get_folder_list(MsgGetCommonHandle(), &folderList)) {
1010             LogError("msg_get_folder_list error");
1011             Throw(WrtDeviceApis::Commons::PlatformException);
1012         }
1013         for (int i = 0; i < folderList.nCount; ++i) {
1014             if (MSG_FOLDER_TYPE_USER_DEF ==
1015                 folderList.folderInfo[i].folderType &&
1016                 NULL != folderList.folderInfo[i].folderName &&
1017                 folder == folderList.folderInfo[i].folderName) {
1018                 result = folderList.folderInfo[i].folderId;
1019                 break;
1020             }
1021         }
1022     }
1023     Catch(WrtDeviceApis::Commons::PlatformException) {
1024         if (folderList.nCount) {
1025             msg_release_folder_list(&folderList);
1026         }
1027         throw;
1028     }
1029     if (folderList.nCount) {
1030         msg_release_folder_list(&folderList);
1031     }
1032 */
1033     return result;
1034 }
1035
1036 void Messaging::addOnMessageReceived(
1037         const Api::Messaging::EmitterMessageReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, int funtionIndex)
1038 {
1039     LogDebug("ENTER");
1040
1041     if(filter != NULL)
1042     {
1043         Try
1044         {
1045             LogDebug("funtionIndex = " << funtionIndex);    
1046             bool isValidFilter = validateFilter(filter, funtionIndex);
1047             if(isValidFilter == false){
1048                 LogError("[ERROR]this filter is invalid");
1049                 Throw(WrtDeviceApis::Commons::InvalidArgumentException);
1050             }    
1051         }
1052         Catch(WrtDeviceApis::Commons::PlatformException) {
1053             throw;
1054         }
1055     }else
1056     {
1057         LogDebug("filter is NULL");     
1058     }
1059
1060         
1061     m_onMessageReceived.attach(emitter);
1062     EmittersMessageReceived::LockType lock = m_onMessageReceived.getLock();
1063     if ((m_onMessageReceived.size() == 1)&&((m_onConversationReceived.size() + m_onFolderReceived.size()) == 0)) {
1064         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(
1065                 new MsgServiceHandleMgr());
1066         int err;
1067         Try{
1068             err = msg_reg_storage_change_callback(
1069             m_onMessageReceivedHandleMgr->getHandle(),
1070             onMessageStorageChanged,
1071             this);
1072         }
1073         Catch(WrtDeviceApis::Commons::PlatformException){
1074             LogDebug("addOnMessageReceived failed");
1075             Throw(WrtDeviceApis::Commons::PlatformException);
1076         }
1077
1078         if (err != MSG_SUCCESS) {
1079             LogError("Couldn't register on MMS received callback, err=" << err);
1080         }
1081
1082         m_dbusConnection->open(DBUS_BUS_SYSTEM);
1083     }
1084 }
1085
1086 void Messaging::addOnMessageReceived(
1087         const Api::Messaging::EmitterConversationReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, int funtionIndex)
1088 {
1089     LogDebug("ENTER");
1090
1091     if(filter != NULL)
1092     {
1093         Try
1094         {
1095             LogDebug("funtionIndex = " << funtionIndex);    
1096             bool isValidFilter = validateFilter(filter, funtionIndex);
1097             if(isValidFilter == false){
1098                 LogError("[ERROR]this filter is invalid");
1099                 Throw(WrtDeviceApis::Commons::InvalidArgumentException);
1100             }    
1101         }
1102         Catch(WrtDeviceApis::Commons::PlatformException) {
1103             throw;
1104         }
1105     }else
1106     {
1107         LogDebug("filter is NULL");     
1108     }
1109
1110         
1111     m_onConversationReceived.attach(emitter);
1112     EmittersConversationReceived::LockType lock = m_onConversationReceived.getLock();
1113     if ((m_onConversationReceived.size() == 1)&&((m_onMessageReceived.size() + m_onFolderReceived.size()) == 0)) {
1114         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(
1115                 new MsgServiceHandleMgr());
1116         int err;
1117         Try{
1118             err = msg_reg_storage_change_callback(
1119             m_onMessageReceivedHandleMgr->getHandle(),
1120             onMessageStorageChanged,
1121             this);
1122         }
1123         Catch(WrtDeviceApis::Commons::PlatformException){
1124             LogDebug("addOnMessageReceived failed");                            
1125             Throw(WrtDeviceApis::Commons::PlatformException);
1126         }
1127
1128         if (err != MSG_SUCCESS) {
1129             LogError("Couldn't register on MMS received callback, err=" << err);
1130         }
1131
1132         m_dbusConnection->open(DBUS_BUS_SYSTEM);
1133     }
1134 }
1135
1136 void Messaging::addOnMessageReceived(
1137         const Api::Messaging::EmitterFolderReceivedPtr& emitter, const Api::Tizen::FilterPtr& filter, int funtionIndex)
1138 {
1139     LogDebug("ENTER");
1140
1141     if(filter != NULL)
1142     {
1143         Try
1144         {
1145             LogDebug("funtionIndex = " << funtionIndex);    
1146             bool isValidFilter = validateFilter(filter, funtionIndex);
1147             if(isValidFilter == false){
1148                 LogError("[ERROR]this filter is invalid");
1149                 Throw(WrtDeviceApis::Commons::InvalidArgumentException);
1150             }    
1151         }
1152         Catch(WrtDeviceApis::Commons::PlatformException) {
1153             throw;
1154         }
1155     }else
1156     {
1157         LogDebug("filter is NULL");     
1158     }
1159
1160         
1161     m_onFolderReceived.attach(emitter);
1162     EmittersFolderReceived::LockType lock = m_onFolderReceived.getLock();
1163     if ((m_onFolderReceived.size() == 1)&&((m_onMessageReceived.size() + m_onConversationReceived.size()) == 0)) {
1164         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(
1165                 new MsgServiceHandleMgr());
1166         int err;
1167
1168         Try
1169         {
1170             err = msg_reg_storage_change_callback(
1171             m_onMessageReceivedHandleMgr->getHandle(),
1172             onMessageStorageChanged,
1173             this);
1174         }
1175         Catch(WrtDeviceApis::Commons::PlatformException){
1176             LogDebug("addOnMessageReceived failed");                            
1177             Throw(WrtDeviceApis::Commons::PlatformException);
1178         }
1179
1180         if (err != MSG_SUCCESS) {
1181             LogError("Couldn't register on MMS received callback, err=" << err);
1182 //              Throw(WrtDeviceApis::Commons::UnknownException);
1183         }
1184
1185         m_dbusConnection->open(DBUS_BUS_SYSTEM);
1186     }
1187 }
1188
1189 bool Messaging::validateFilter(const Api::Tizen::FilterPtr& filter, const int funtionIndex){
1190         LogDebug("<<<");
1191
1192         bool retBool = false;
1193         LogDebug("funtionIndex = " << funtionIndex);    
1194
1195         if(filter != NULL){
1196                 if(funtionIndex == 0)
1197                 {
1198                         Platform::Messaging::StorageChangesMessageFilterValidatorPtr validatorMsg =
1199                                         Platform::Messaging::StorageChangesMessageFilterValidatorFactory::getStorageChangesMessageFilterValidator();
1200
1201                         FilterValidatorPtr filterValidatorMsg = DPL::StaticPointerCast<FilterValidator>(validatorMsg);
1202                         retBool = filter->validate(filterValidatorMsg);
1203                 }else if(funtionIndex == 1)
1204                 {
1205                         Platform::Messaging::StorageChangesConversationFilterValidatorPtr validatorConv =
1206                                         Platform::Messaging::StorageChangesConversationFilterValidatorFactory::getStorageChangesConversationFilterValidator();
1207
1208                         FilterValidatorPtr filterValidatorConv = DPL::StaticPointerCast<FilterValidator>(validatorConv);
1209                         retBool = filter->validate(filterValidatorConv);
1210                 }else if(funtionIndex == 2)
1211                 {
1212                         Platform::Messaging::StorageChangesFolderFilterValidatorPtr validatorFolder =
1213                                         Platform::Messaging::StorageChangesFolderFilterValidatorFactory::getStorageChangesFolderFilterValidator();
1214
1215                         FilterValidatorPtr filterValidatorFolder = DPL::StaticPointerCast<FilterValidator>(validatorFolder);
1216                         retBool = filter->validate(filterValidatorFolder);
1217                 }
1218                 
1219                 if(retBool == false){
1220                         Throw(WrtDeviceApis::Commons::InvalidArgumentException);
1221                 }
1222         }else{
1223                 LogDebug("filter is NULL");
1224                 retBool = false;
1225         }
1226
1227         LogDebug(">>> retBool:" << retBool);
1228         return retBool;
1229
1230 }
1231
1232
1233 void Messaging::removeOnMessageMsgReceived(Api::Messaging::EmitterMessageReceived::IdType id)
1234 {
1235     LogDebug("ENTER");
1236     m_onMessageReceived.detach(id);
1237     EmittersMessageReceived::LockType lock = m_onMessageReceived.getLock();
1238     if ((m_onMessageReceived.size()+m_onConversationReceived.size()+m_onFolderReceived.size()) == 0) {
1239         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(NULL);
1240         m_dbusConnection->close();
1241     }
1242 }
1243
1244 void Messaging::removeOnMessageConvReceived(Api::Messaging::EmitterConversationReceived::IdType id)
1245 {
1246     LogDebug("ENTER");
1247     m_onConversationReceived.detach(id);
1248     EmittersConversationReceived::LockType lock = m_onConversationReceived.getLock();
1249     if ((m_onMessageReceived.size()+m_onConversationReceived.size()+m_onFolderReceived.size()) == 0) {
1250         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(NULL);
1251         m_dbusConnection->close();
1252     }
1253 }
1254
1255 void Messaging::removeOnMessageFolderReceived(Api::Messaging::EmitterFolderReceived::IdType id)
1256 {
1257     LogDebug("ENTER");
1258     m_onFolderReceived.detach(id);
1259     EmittersFolderReceived::LockType lock = m_onFolderReceived.getLock();
1260     if ((m_onMessageReceived.size()+m_onConversationReceived.size()+m_onFolderReceived.size()) == 0) {
1261         m_onMessageReceivedHandleMgr = MsgServiceHandleMgrPtr(NULL);
1262         m_dbusConnection->close();
1263     }
1264 }
1265
1266 void Messaging::OnEventReceived(const DBus::MessageEvent& event)
1267 {
1268         LogDebug("ENTER");
1269         EventMessageReceivedPtr jsEvent(new EventMessageReceived());
1270         DBus::MessagePtr message = event.GetArg0();
1271
1272         if (!message) 
1273         {
1274                 jsEvent->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::PlatformException);
1275                 m_onMessageReceived.emit(jsEvent);
1276         } 
1277         else 
1278         {
1279                 if (message->getInterface() == DBUS_INTERFACE_EMAIL_RECEIVED) 
1280                 {
1281                         int account_id = 0, mail_id = 0, thread_id = 0, status = 0;
1282                         std::string name;
1283                         email_mailbox_t m_mailboxes;            
1284                         email_mailbox_t* mailboxes = NULL;
1285
1286                         DBus::Message::ReadIterator it = message->getReadIterator();
1287                         for (int i = 0; it->isValid(); it->next(), ++i) 
1288                         {
1289                                 if ((i == 0) && (it->getArgType() == DBUS_TYPE_INT32)) 
1290                                 {
1291                                         status = it->getInt();
1292                                         LogInfo("status: " << status);                                  
1293                                 } 
1294                                 else if ((i == 1) && (it->getArgType() == DBUS_TYPE_INT32)) 
1295                                 {
1296                                         account_id = it->getInt();
1297                                         LogInfo("account_id: " << account_id);                                  
1298                                 } 
1299                                 else if ((i == 2) && (it->getArgType() == DBUS_TYPE_INT32)) 
1300                                 {
1301                                         mail_id = it->getInt();
1302                                         LogInfo("mail_id: " << mail_id);                                                                                
1303                                 } 
1304                                 else if ((i == 3) && (it->getArgType() == DBUS_TYPE_STRING)) 
1305                                 {
1306                                         name = it->getString();
1307                                         LogInfo("name: " << name);                                                                              
1308                                 } 
1309                                 else if ((i == 4) && (it->getArgType() == DBUS_TYPE_INT32)) 
1310                                 {
1311                                         thread_id = it->getInt();
1312                                         LogInfo("thread_id: " << thread_id);                                                                            
1313                                 }
1314                         }
1315
1316                         if ((mail_id > 0) && (NOTI_MAIL_ADD == status)) 
1317                         { // TODO also RECEIVE_THREAD_ITEM?
1318                                 LogInfo("Email received. mail_id: " << mail_id);
1319
1320                                 IMessagePtr msg = MessageFactory::createMessage(EMAIL, mail_id);
1321                                 IConversationPtr conversation(new Conversation(thread_id, EMAIL));
1322
1323                                 // TODO Temporary fix: ignore messages from OUTBOX, SENTBOX & DRAFTBOX -> most probably we added them
1324                                 Api::Messaging::FolderType folder = msg->getCurrentFolder();
1325                                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1326
1327                                 if (OUTBOX != folder && SENTBOX != folder && DRAFTBOX != folder)
1328                                 {
1329                                         jsEvent->setMessage(msg);
1330                                         jsEvent->setConversation(conversation);
1331
1332                                         if(m_onMessageReceived.size() > 0){
1333                                                 m_onMessageReceived.emit(jsEvent);
1334                                         }
1335
1336                                         if(m_onConversationReceived.size() > 0){
1337                                         m_onConversationReceived.emit(jsEvent);
1338                                         }
1339
1340                                 } else {
1341                                         LogWarning("New email message in ignored folder: " << folder);
1342                                 }
1343                         }
1344                         else if ((mail_id > 0) && (NOTI_MAIL_DELETE == status))
1345                         { // TODO also RECEIVE_THREAD_ITEM?
1346                                 LogInfo("Email received. delete type: " << mail_id);
1347
1348                                 std::vector<std::string> strIds = String::split(name, ',');
1349
1350                                 std::stringstream stream;
1351                                 for (std::vector<std::string>::iterator it = strIds.begin(); it != strIds.end(); ++it)
1352                                 {
1353                                         LogDebug("ID is :" << *it);
1354
1355                                         if ( (*it).length() > 0 ) //vaild id
1356                                         {
1357                                                 stream<< *it;
1358                                                 int id;
1359                                                 stream >> id;
1360
1361                                                 IMessagePtr msg = MessageFactory::createMessage(EMPTY_MESSAGE, id);
1362                                                 IConversationPtr conversation(new Conversation());
1363
1364                                                 Api::Messaging::FolderType folder = msg->getCurrentFolder();
1365                                                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_DELETED);
1366
1367                                                 if (true) { // if (OUTBOX != folder && SENTBOX != folder && DRAFTBOX != folder)
1368                                                         jsEvent->setMessage(msg);
1369                                                         jsEvent->setConversation(conversation);
1370                                                         if(m_onMessageReceived.size() > 0){
1371                                                                 m_onMessageReceived.emit(jsEvent);
1372                                                         }
1373                                                 }
1374                                                 else {
1375                                                         LogWarning("New email message in ignored folder: " << folder);
1376                                                 }
1377                                         }
1378
1379                                         stream.clear();
1380                                 } //for
1381
1382                         }
1383                         else if ((mail_id > 0) && (NOTI_MAIL_UPDATE == status)) 
1384                         { // TODO also RECEIVE_THREAD_ITEM?
1385                                 LogInfo("Email received. mail_id: " << mail_id);
1386
1387                                 IMessagePtr msg = MessageFactory::createMessage(EMAIL, mail_id);
1388                                 IConversationPtr conversation(new Conversation(thread_id, EMAIL));
1389
1390                                 Api::Messaging::FolderType folder = msg->getCurrentFolder();
1391                                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED);
1392
1393                                 if (true) { // if (OUTBOX != folder && SENTBOX != folder && DRAFTBOX != folder)
1394                                         jsEvent->setMessage(msg);
1395                                         jsEvent->setConversation(conversation);
1396                                         if(m_onMessageReceived.size() > 0)
1397                                                 m_onMessageReceived.emit(jsEvent);
1398                                         if(m_onConversationReceived.size() > 0)
1399                                                 m_onConversationReceived.emit(jsEvent);
1400                                 } else {
1401                                         LogWarning("New email message in ignored folder: " << folder);
1402                                 }
1403                         }
1404                         else if ((mail_id > 0) && (NOTI_THREAD_DELETE == status))
1405                         { // TODO also RECEIVE_THREAD_ITEM?
1406                                 LogInfo("Email received. delete thread Id : " << mail_id);
1407
1408                                 IConversationPtr conversation(new Conversation());
1409                                 conversation->setId((unsigned int)mail_id);
1410                                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_DELETED);
1411                                 jsEvent->setConversation(conversation);
1412
1413                                 if(m_onConversationReceived.size() > 0){
1414                                         m_onConversationReceived.emit(jsEvent);
1415                                 }
1416                         }
1417                         else if (NOTI_MAILBOX_ADD == status)
1418                         {
1419                                 LogInfo("Emailbox received. account Id: " << account_id);
1420                                 LogInfo("name Id: " << name);
1421
1422                                 email_mail_data_t* mail_data = NULL;
1423                                 email_mailbox_t* mail_box = NULL;
1424
1425                                 if (EMAIL_ERROR_NONE != email_get_mail_data(mail_id, &mail_data)) {
1426                                         LogError("Couldn't retrieve message or it has been malformed.");
1427                                 }
1428                                 if (EMAIL_ERROR_NONE != email_get_mailbox_by_mailbox_id(mail_data->mailbox_id, &mail_box)) {
1429                                         LogError("Couldn't retrieve message or it has been malformed.");
1430                                 }
1431
1432                                 //                email_get_mailbox_by_name(account_id, name.c_str(), &mail_box);
1433
1434                                 m_mailboxes = *mail_box;
1435
1436                                 Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes));
1437                                 jsEvent->setMessageFolder(folderPtr);
1438                                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1439                                 if(m_onFolderReceived.size() > 0)
1440                                 {
1441                                         m_onFolderReceived.emit(jsEvent);
1442                                 }
1443
1444                         }
1445                         else if (NOTI_MAILBOX_UPDATE == status) 
1446                         {
1447                                 LogInfo("Emailbox received. account Id: " << account_id);
1448                                 LogInfo("name Id: " << name);
1449
1450                                 email_mail_data_t* mail_data = NULL;
1451                                 email_mailbox_t* mail_box = NULL;
1452
1453                                 if (EMAIL_ERROR_NONE != email_get_mail_data(mail_id, &mail_data)) {
1454                                         LogError("Couldn't retrieve message or it has been malformed.");
1455                                 }
1456                                 if (EMAIL_ERROR_NONE != email_get_mailbox_by_mailbox_id(mail_data->mailbox_id, &mail_box)) {
1457                                         LogError("Couldn't retrieve message or it has been malformed.");
1458                                 }
1459
1460                                 //            email_get_mailbox_by_name(account_id, name.c_str(), &mailboxes);
1461
1462                                 m_mailboxes = *mail_box;
1463
1464                                 Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes));
1465                                 jsEvent->setMessageFolder(folderPtr);
1466                                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED);
1467
1468                                 if(m_onFolderReceived.size() > 0)
1469                                 {
1470                                         m_onFolderReceived.emit(jsEvent);
1471                                 }
1472                         }
1473                         else if (NOTI_MAILBOX_DELETE == status) 
1474                         {
1475                                 LogInfo("Emailbox received. account Id: " << account_id);
1476                                 LogInfo("name Id: " << name);
1477
1478                                 email_mail_data_t* mail_data = NULL;
1479                                 email_mailbox_t* mail_box = NULL;
1480
1481                                 if (EMAIL_ERROR_NONE != email_get_mail_data(mail_id, &mail_data)) {
1482                                         LogError("Couldn't retrieve message or it has been malformed.");
1483                                 }
1484                                 if (EMAIL_ERROR_NONE != email_get_mailbox_by_mailbox_id(mail_data->mailbox_id, &mail_box)) {
1485                                         LogError("Couldn't retrieve message or it has been malformed.");
1486                                 }
1487
1488                                 //                email_get_mailbox_by_name(account_id, name.c_str(), &mail_box);
1489
1490                                 m_mailboxes = *mail_box;
1491
1492                                 Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes));
1493                                 jsEvent->setMessageFolder(folderPtr);
1494                                 jsEvent->setMsg_Event_Type(EventMessageReceived::MSG_DELETED);
1495
1496                                 if(m_onFolderReceived.size() > 0)
1497                                 {
1498                                         m_onFolderReceived.emit(jsEvent);
1499                                 }
1500                         }
1501                         else 
1502                         {
1503                                 LogError("Couldn't retrieve message or it has been malformed.");
1504                         }
1505                 } 
1506                 else // DBUS_INTERFACE_EMAIL_RECEIVED
1507                 {
1508                         LogDebug("Wrong DBus interface, skipping it.");
1509                 }
1510         }
1511 }
1512
1513 void Messaging::onMessageStorageChanged(msg_handle_t handle,
1514         msg_storage_change_type_t storageChangeType,
1515         msg_id_list_s *pMsgIdList,
1516         void* data)
1517 {
1518
1519     LogDebug("ENTER");
1520
1521     msg_error_t err = MSG_SUCCESS;
1522
1523     if(storageChangeType == MSG_STORAGE_CHANGE_CONTACT)
1524     {
1525         LogDebug("storageChangeType is MSG_STORAGE_CHANGE_CONTACT");    
1526         return;
1527     }
1528         
1529     Messaging* this_ = static_cast<Messaging*>(data);
1530     if (this_) 
1531     {
1532         Try {
1533             int msgCount = pMsgIdList->nCount;
1534             LogDebug("msgCount = "<< msgCount);
1535
1536             for(int index = 0; index < msgCount; index++)
1537             {
1538
1539             LogDebug("storageChangeType = "<< storageChangeType);
1540                         
1541                 if(storageChangeType == MSG_STORAGE_CHANGE_DELETE)
1542                 {
1543                     IMessagePtr message = MessageFactory::createMessage(EMPTY_MESSAGE, pMsgIdList->msgIdList[index]);
1544                     IConversationPtr conversation(new Conversation());                                  
1545                     EventMessageReceivedPtr event(new EventMessageReceived());
1546                     event->setMessage(message);
1547                     event->setConversation(conversation);
1548                     event->setMsg_Event_Type(EventMessageReceived::MSG_DELETED);
1549
1550                     if(this_->m_onMessageReceived.size() > 0){
1551                         this_->m_onMessageReceived.emit(event);
1552                     }
1553                     if(this_->m_onConversationReceived.size() > 0){
1554                         this_->m_onConversationReceived.emit(event);
1555                     }
1556                 }
1557                 else
1558                 {
1559                     msg_struct_t msg = NULL;
1560                     msg_struct_t sendOpt = NULL;
1561                     msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
1562                     sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
1563                         
1564                     err = msg_get_message(handle, pMsgIdList->msgIdList[index], msg, sendOpt);
1565
1566                     if (err != MSG_SUCCESS)
1567                     {
1568                         LogDebug("Get Message Failed!");
1569                         LogDebug("err" << err); 
1570                         msg_release_struct(&msg);
1571                         msg_release_struct(&sendOpt);
1572                         return;
1573                     }
1574                     int msgType = 0;
1575                     msg_get_int_value(msg, MSG_MESSAGE_TYPE_INT, &msgType);
1576                    LogDebug("msgType : " << msgType); 
1577                     if((msgType > MSG_TYPE_INVALID) && ( msgType <= MSG_TYPE_SMS_REJECT))
1578                     {
1579                         if(msgType  != MSG_TYPE_MMS_NOTI)
1580                         {
1581                             int msgId = 0;
1582                             msg_get_int_value(msg, MSG_MESSAGE_ID_INT, &msgId);
1583                             IMessagePtr message = MessageFactory::createMessage(
1584                                                                                 SMS,
1585                                                                                 msgId,
1586                                                                                 msg
1587                                                                                 );
1588                             ISmsPtr sms = MessageFactory::convertToSms(message);
1589                             IConversationPtr conversation(new Conversation(message->getId(), SMS));
1590                             EventMessageReceivedPtr event(new EventMessageReceived());
1591                             event->setMessage(message);
1592                             event->setConversation(conversation);
1593
1594                             if(storageChangeType == MSG_STORAGE_CHANGE_INSERT)
1595                             {
1596                                 event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1597                             }
1598                             else if(storageChangeType == MSG_STORAGE_CHANGE_UPDATE)
1599                             {
1600                                 event->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED);
1601                             }
1602 //                              else if(storageChangeType == MSG_STORAGE_CHANGE_DELETE)
1603 //                              {
1604 //                                  event->setMsg_Event_Type(EventMessageReceived::MSG_DELETED);
1605 //                              }
1606
1607                             if(this_->m_onMessageReceived.size() > 0){
1608                                 this_->m_onMessageReceived.emit(event);
1609                             }
1610                             if(this_->m_onConversationReceived.size() > 0){
1611                                 this_->m_onConversationReceived.emit(event);
1612                             }
1613                         }
1614                         else
1615                         {
1616                             LogError("Ignore this sms, this is mms noti.");
1617                         }
1618                     }
1619                     else if((msgType >= MSG_TYPE_MMS) && (msgType <= MSG_TYPE_MMS_NOTI))
1620                     {
1621                         if(msgType  != MSG_TYPE_MMS_NOTI)
1622                         {
1623                             int msgId = 0;
1624                             msg_get_int_value(msg, MSG_MESSAGE_ID_INT, &msgId);
1625                             IMessagePtr message = MessageFactory::createMessage(
1626                                                                                 MMS,
1627 //                                                                                msg_get_message_id(
1628                                                                                 msgId,
1629                                                                                 msg
1630                                                                                 );
1631                             IMmsPtr mms = MessageFactory::convertToMms(message);
1632                             IConversationPtr conversation(new Conversation(message->getId(), MMS));
1633                             EventMessageReceivedPtr event(new EventMessageReceived());
1634                             event->setMessage(message);
1635                             event->setConversation(conversation);
1636
1637                             if(storageChangeType == MSG_STORAGE_CHANGE_INSERT)
1638                             {
1639                                 event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1640                             }
1641                             else if(storageChangeType == MSG_STORAGE_CHANGE_UPDATE)
1642                             {
1643                                 event->setMsg_Event_Type(EventMessageReceived::MSG_UPDATED);
1644                             }
1645 //                              else if(storageChangeType == MSG_STORAGE_CHANGE_DELETE)
1646 //                              {
1647 //                                  event->setMsg_Event_Type(EventMessageReceived::MSG_DELETED);
1648 //                              }
1649
1650                             if(this_->m_onMessageReceived.size() > 0){
1651                                 this_->m_onMessageReceived.emit(event);
1652                             }
1653                             if(this_->m_onConversationReceived.size() > 0){
1654                                 this_->m_onConversationReceived.emit(event);
1655                             }
1656                         }
1657                         else
1658                         {
1659                             LogError("Ignore this mms, this is mms noti.");
1660                         }
1661                     }
1662                                         
1663                     msg_release_struct(&msg);
1664                     msg_release_struct(&sendOpt);                                       
1665                 }
1666             }
1667         }
1668         Catch(WrtDeviceApis::Commons::ConversionException) {
1669             LogError("Couldn't convert message to sms.");
1670         }
1671         Catch(WrtDeviceApis::Commons::PlatformException) {
1672             LogError("onMessageStorageChanged platform exception");
1673         }               
1674     }
1675 }
1676
1677 /*
1678 void Messaging::onSmsReceived(MSG_HANDLE_T handle,
1679         msg_message_t msg,
1680         void* data)
1681 {
1682     LogDebug("ENTER");
1683     Messaging* this_ = static_cast<Messaging*>(data);
1684     if (this_) {
1685         Try {
1686                         if(msg_get_message_type(msg) != MSG_TYPE_MMS_NOTI)
1687                         {
1688             IMessagePtr message = MessageFactory::createMessage(
1689                     SMS,
1690                     msg_get_message_id(
1691                         msg));
1692             ISmsPtr sms = MessageFactory::convertToSms(message);
1693             IConversationPtr conversation(new Conversation(message->getId(), SMS));
1694                         
1695             EventMessageReceivedPtr event(new EventMessageReceived());
1696             event->setMessage(message);
1697             event->setConversation(conversation);
1698                         event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1699                         this_->m_onMessageReceived.emit(event);
1700         }
1701                         else
1702                         {
1703                                 LogError("Ignore this sms, this is mms noti.");
1704                         }
1705         }
1706         Catch(WrtDeviceApis::Commons::ConversionException) {
1707             LogError("Couldn't convert message to sms.");
1708         }
1709     }
1710 }
1711
1712 void Messaging::onMmsReceived(MSG_HANDLE_T handle,
1713         msg_message_t msg,
1714         void* data)
1715 {
1716     LogDebug("ENTER");
1717     Messaging* this_ = static_cast<Messaging*>(data);
1718     if (this_) {
1719         Try {
1720             IMessagePtr message = MessageFactory::createMessage(
1721                     MMS,
1722                     msg_get_message_id(
1723                         msg));
1724             IMmsPtr mms = MessageFactory::convertToMms(message);
1725             IConversationPtr conversation(new Conversation(message->getId(), MMS));
1726             EventMessageReceivedPtr event(new EventMessageReceived());
1727             event->setMessage(message);
1728             event->setConversation(conversation);
1729                         event->setMsg_Event_Type(EventMessageReceived::MSG_ADDED);
1730                         this_->m_onMessageReceived.emit(event);
1731         }
1732         Catch(WrtDeviceApis::Commons::ConversionException) {
1733             LogError("Couldn't convert message to mms.");
1734         }
1735     }
1736 }
1737
1738 void Messaging::getNumberOfEmails(Api::Messaging::FolderType folder,
1739         int* read,
1740         int* unread)
1741 {
1742     LOG_ENTER
1743
1744     email_mailbox_t mailbox = {};
1745     mailbox.account_id = 0; // means for all accounts
1746     mailbox.name = String::strdup(
1747             EmailConverter::toMailboxName(folder)
1748             );
1749
1750     int error = email_count_mail(&mailbox, read, unread);
1751     free(mailbox.name);
1752
1753     if (EMAIL_ERROR_NONE != error) {
1754         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1755                  "Couldn't get number of emails. [" << error << "]");
1756     }
1757
1758     LOG_EXIT
1759 }
1760
1761 void Messaging::getNumberOfSms(Api::Messaging::FolderType folder,
1762         int* read,
1763         int* unread)
1764 {
1765     getNumberOfSmsMms(folder, read, unread, SMS);
1766 }
1767
1768 void Messaging::getNumberOfMms(Api::Messaging::FolderType folder,
1769         int* read,
1770         int* unread)
1771 {
1772     getNumberOfSmsMms(folder, read, unread, MMS);
1773 }
1774
1775 void Messaging::getNumberOfSmsMms(Api::Messaging::FolderType folder,
1776         int* read,
1777         int* unread,
1778         Api::Messaging::MessageType msgType)
1779 {
1780     MSG_LIST_S folderListView = { 0, NULL };
1781
1782     *read = 0;
1783     *unread = 0;
1784
1785     Try
1786     {
1787         MSG_MESSAGE_TYPE_T msgTypePlatform;
1788         if (SMS == msgType) {
1789             msgTypePlatform = MSG_TYPE_SMS;
1790         } else if (MMS == msgType) {
1791             msgTypePlatform = MSG_TYPE_MMS;
1792         } else {
1793             LogError("no supported message type in this method");
1794             Throw(WrtDeviceApis::Commons::PlatformException);
1795         }
1796
1797         msg_folder_id_t msgFolderId;
1798         switch (folder) {
1799         case INBOX:
1800             msgFolderId = MSG_INBOX_ID;
1801             break;
1802         case OUTBOX:
1803             msgFolderId = MSG_OUTBOX_ID;
1804             break;
1805         case SENTBOX:
1806             msgFolderId = MSG_SENTBOX_ID;
1807             break;
1808         case DRAFTBOX:
1809             msgFolderId = MSG_DRAFT_ID;
1810             break;
1811         default:
1812             LogError("wrong folder type");
1813             Throw(WrtDeviceApis::Commons::PlatformException);
1814             break;
1815         }
1816
1817         const MSG_SORT_RULE_S sort_rules = { MSG_SORT_BY_DISPLAY_TIME, true };
1818         if (msg_get_folder_view_list(MsgGetCommonHandle(), msgFolderId,
1819                                      &sort_rules,
1820                                      &folderListView) != MSG_SUCCESS) {
1821             LogDebug(
1822                 "msg_get_folder_view_list empty or failed, msgFolderId=" <<
1823                 (int) msgFolderId);
1824             Throw(WrtDeviceApis::Commons::PlatformException);
1825         }
1826         // go thtough all message to check type of message
1827         LogDebug("msgCount=" << (int) folderListView.nCount);
1828         for (int msg_cnt = 0; msg_cnt < folderListView.nCount; msg_cnt++) {
1829             LogDebug("msgMainType=" <<
1830                                          (int) msg_get_message_type(folderListView.
1831                                                                         msgInfo[
1832                                                                 msg_cnt]) <<
1833                      ", searching for = " << (int) msgTypePlatform);
1834             if (msgTypePlatform ==
1835                                 msg_get_message_type(folderListView.msgInfo[
1836                                                      msg_cnt])) {
1837                 if (msg_is_read(folderListView.msgInfo[msg_cnt]))
1838                 {
1839                     (*read)++;
1840                 } else {
1841                     (*unread)++;
1842                 }
1843             }
1844         }
1845                 msg_release_list_struct(&folderListView);
1846
1847         LogDebug("readed=" << *read << ", unReaded=" << *unread);
1848     }
1849
1850     Catch(WrtDeviceApis::Commons::PlatformException) {
1851         if (folderListView.nCount) {
1852                         msg_release_list_struct(&folderListView);
1853         }
1854         throw;
1855     }
1856 }
1857
1858         vector<Api::Messaging::IMessagePtr> Messaging::findSms(Api::Messaging::FolderType folder, const Api::Tizen::FilterPtr& filter)
1859         {
1860                 LogDebug("<<<");
1861
1862                 vector<Api::Messaging::IMessagePtr> retVal;
1863                 msg_message_t msg = msg_new_message();
1864                 MSG_LIST_S folder_list_view = {0, NULL};
1865
1866                 Try{
1867                         const MSG_SORT_RULE_S sort_rules = {MSG_SORT_BY_DISPLAY_TIME, true};
1868                         msg_error_t res = MSG_ERR_UNKNOWN;
1869                         const msg_folder_id_t platformFolder = convertFolderToPlatform(folder);
1870                         res = msg_get_folder_view_list(MsgGetCommonHandle(), platformFolder, &sort_rules, &folder_list_view);
1871
1872                         if (MSG_SUCCESS != res) {
1873                                 LogError("msg_get_folder_view_list failed " << res);
1874                                 Throw(WrtDeviceApis::Commons::PlatformException);
1875                         }
1876
1877                         for (int i = 0; i < folder_list_view.nCount; i++) {
1878                                 if (MSG_TYPE_SMS == msg_get_message_type(folder_list_view.msgInfo[i])) {
1879                                         int l_msgId = msg_get_message_id(folder_list_view.msgInfo[i]);
1880                                         Api::Messaging::IMessagePtr msg = MessageFactory::createMessage(SMS, l_msgId);
1881
1882                                         //                if (!filter || !filter->isValid() ||
1883                                         //                    filter->compare(MessageFactory::convertToSms(msg))) {
1884                                                             retVal.push_back(msg);
1885                                         //                }
1886                                 }
1887                         }
1888
1889                         msg_release_list_struct(&folder_list_view);
1890                 }Catch(WrtDeviceApis::Commons::PlatformException) {
1891                         LogError("Problem with message creation, cleaning");
1892                         if (folder_list_view.nCount) {
1893                                 msg_release_list_struct(&folder_list_view);
1894                         }
1895                         if (msg) {
1896                                 msg_release_message(&msg);
1897                         }
1898                         throw;
1899                 }
1900
1901                 LogDebug(">>>");
1902                 return retVal;
1903         }
1904
1905         vector<Api::Messaging::IMessagePtr> Messaging::findMms(Api::Messaging::FolderType folder,
1906                         const Api::Tizen::FilterPtr& filter)
1907         {
1908                 vector<Api::Messaging::IMessagePtr> retVal;
1909                 msg_message_t msg = msg_new_message();
1910                 MSG_LIST_S folder_list_view = {0, NULL};
1911
1912                 Try
1913                 {
1914                         const MSG_SORT_RULE_S sort_rules = {MSG_SORT_BY_DISPLAY_TIME, true};
1915                         msg_error_t res = MSG_ERR_UNKNOWN;
1916                         const msg_folder_id_t platformFolder = convertFolderToPlatform(folder);
1917                         res = msg_get_folder_view_list(
1918                                         MsgGetCommonHandle(), platformFolder, &sort_rules,
1919                                         &folder_list_view);
1920
1921                         if (MSG_SUCCESS != res) {
1922                                 LogError("msg_Get_folder_view_list failed" << res);
1923                                 Throw(WrtDeviceApis::Commons::PlatformException);
1924                         }
1925
1926                         for (int i = 0; i < folder_list_view.nCount; i++) {
1927                                 if (MSG_TYPE_MMS ==
1928                                                 msg_get_message_type(folder_list_view.
1929                                                                 msgInfo[i])) {
1930                                         int l_msgId = msg_get_message_id(
1931                                                         folder_list_view.msgInfo[i]);
1932                                         Api::Messaging::IMessagePtr msg = MessageFactory::createMessage(MMS, l_msgId);
1933                                 }
1934                         }
1935
1936                         msg_release_list_struct(&folder_list_view);
1937                 }
1938
1939                 Catch(WrtDeviceApis::Commons::PlatformException) {
1940                         LogError("Problem with message creation, cleaning");
1941                         if (folder_list_view.nCount) {
1942                                 msg_release_list_struct(&folder_list_view);
1943                         }
1944                         if (msg) {
1945                                 msg_release_message(&msg);
1946                         }
1947                         throw;
1948                 }
1949
1950                 return retVal;
1951         }
1952 */
1953 void Messaging::createFolder(MessageType msgType,
1954         const string& userFolder)
1955 {
1956     switch (msgType) {
1957     case Api::Messaging::SMS:
1958     case Api::Messaging::MMS:
1959         createMsgServiceFolder(userFolder);
1960         break;
1961     case Api::Messaging::EMAIL:
1962         createEmailFolder(userFolder);
1963         break;
1964     default:
1965         LogError("msg not supported");
1966         Throw(WrtDeviceApis::Commons::UnknownException);
1967     }
1968 }
1969
1970 void Messaging::createMsgServiceFolder(const std::string& userFolder)
1971 {
1972 /*
1973     if (userFolder.length() > MAX_FOLDER_NAME_SIZE) {
1974         LogError("folder name to long");
1975         Throw(WrtDeviceApis::Commons::PlatformException);
1976     }
1977
1978     MSG_FOLDER_INFO_S folderInfo;
1979
1980     folderInfo.folderId = 0;
1981     strncpy(folderInfo.folderName, userFolder.c_str(), userFolder.length());
1982
1983     folderInfo.folderType = MSG_FOLDER_TYPE_USER_DEF;
1984
1985     if (msg_add_folder(MsgGetCommonHandle(), &folderInfo) != MSG_SUCCESS) {
1986         LogError("msg_add_folder failed");
1987         Throw(WrtDeviceApis::Commons::PlatformException);
1988     }
1989 */
1990 }
1991
1992 void Messaging::createEmailFolder(const std::string& userFolder)
1993 {
1994     //TODO
1995     LogError("TODO");
1996     Throw(WrtDeviceApis::Commons::UnknownException);
1997 }
1998
1999 void Messaging::deleteFolder(MessageType msgType,
2000         const string& userFolder)
2001 {
2002     switch (msgType) {
2003     case Api::Messaging::SMS:
2004     case Api::Messaging::MMS:
2005         deleteMsgServiceFolder(userFolder);
2006         break;
2007     case Api::Messaging::EMAIL:
2008         deleteEmailFolder(userFolder);
2009         break;
2010     default:
2011         LogError("msg not supported");
2012         Throw(WrtDeviceApis::Commons::UnknownException);
2013     }
2014 }
2015
2016 void Messaging::deleteMsgServiceFolder(const string& userFolder)
2017 {
2018 /*
2019     Try
2020     {
2021         int platformFolderId = convertFolderToPlatform(userFolder);
2022         if (MSG_SUCCESS !=
2023             msg_delete_folder(MsgGetCommonHandle(), platformFolderId)) {
2024             LogError("msg_get_folder_list failed");
2025             Throw(WrtDeviceApis::Commons::PlatformException);
2026         }
2027     }
2028     Catch(WrtDeviceApis::Commons::PlatformException) {
2029         throw;
2030     }
2031 */
2032 }
2033
2034 void Messaging::deleteEmailFolder(const string& userFolder)
2035 {
2036     //TODO
2037     LogError("TODO");
2038     Throw(WrtDeviceApis::Commons::UnknownException);
2039 }
2040
2041 vector<string> Messaging::getFolderNames(MessageType msgType)
2042 {
2043     switch (msgType) {
2044     case Api::Messaging::SMS:
2045     case Api::Messaging::MMS:
2046         return getFolderNamesMsgService();
2047     case Api::Messaging::EMAIL:
2048         return getFolderNamesEmail();
2049     default:
2050         LogError("msg not supported");
2051         Throw(WrtDeviceApis::Commons::UnknownException);
2052     }
2053 }
2054
2055 vector<string> Messaging::getFolderNamesMsgService()
2056 {
2057     vector<string> retVal;
2058 //    MSG_FOLDER_LIST_S msgFolderList = { 0, NULL }; // output data
2059 /*
2060     msg_struct_list_s msgFolderList = {0,};
2061
2062     Try
2063     {
2064         if (msg_get_folder_list(MsgGetCommonHandle(),
2065                                 &msgFolderList) != MSG_SUCCESS) {
2066             LogError("msg_get_folder_list failed");
2067             Throw(WrtDeviceApis::Commons::PlatformException);
2068         }
2069
2070         LogDebug("number of folder=" << msgFolderList.nCount);
2071         for (int i = 0; i < msgFolderList.nCount; i++) {
2072             LogDebug("folderName=" << msgFolderList.folderInfo[i].folderName);
2073             LogDebug("folderId=" << (int) msgFolderList.folderInfo[i].folderId);
2074             LogDebug(
2075                 "folderType=" <<
2076                 (int) msgFolderList.folderInfo[i].folderType);
2077             retVal.push_back(msgFolderList.folderInfo[i].folderName);
2078         }
2079         (void) msg_release_folder_list(&msgFolderList);
2080     }
2081
2082     Catch(WrtDeviceApis::Commons::PlatformException) {
2083         if (msgFolderList.nCount) {
2084             (void) msg_release_folder_list(&msgFolderList);
2085         }
2086         throw;
2087     }
2088     */
2089     return retVal;
2090 }
2091
2092 vector<string> Messaging::getFolderNamesEmail()
2093 {
2094     vector<string> retVal;
2095
2096     string tmpStr;
2097     email_mailbox_t* mailboxes = NULL;
2098     int mailboxesCount;
2099     string emailAccountName;
2100     Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount();
2101
2102     Try
2103     {
2104         if (!email_get_mailbox_list(account.getIntId(), -1, &mailboxes,
2105                                     &mailboxesCount) || !mailboxes) {
2106             LogError("error during get mailboxes");
2107         }
2108         for (int i = 0; i < mailboxesCount; i++) {
2109             retVal.push_back(mailboxes->mailbox_name);
2110             LogDebug("mailbox found, name=" << mailboxes->mailbox_name);
2111             mailboxes++;
2112         }
2113     }
2114
2115     Catch(WrtDeviceApis::Commons::PlatformException) {
2116         // nothing to clean, re-throw exception
2117         throw;
2118     }
2119
2120     return retVal;
2121 }
2122 /*
2123 vector<Api::Messaging::IMessagePtr> Messaging::findEmail(const std::string &folder,
2124                 const Api::Tizen::FilterPtr& filter)
2125 {
2126     vector<Api::Messaging::IMessagePtr> retVal;
2127
2128     Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount();
2129     if (account.getId().empty()) {
2130         LogWarning("No valid email accounts. Skipping");
2131         return retVal;
2132     }
2133
2134     int accountId = account.getIntId();
2135
2136     // number of found emails
2137     int count = 0;
2138     // start index
2139     int startIndex = 0;
2140
2141     do {
2142         email_mail_list_item_t* results = NULL;
2143         int err = email_get_mail_list(accountId,
2144                                          folder.c_str(),
2145                                          EMAIL_LIST_TYPE_NORMAL,
2146                                          startIndex,
2147                                          MESSAGE_FIND_LIMIT,
2148                                          EMAIL_SORT_DATETIME_HIGH,
2149                                          &results,
2150                                          &count);
2151         DPL::ScopedFree<email_mail_list_item_t> autoFree(results);
2152         (void)autoFree;
2153         if (EMAIL_ERROR_MAIL_NOT_FOUND == err || results == NULL) {
2154             LogWarning("No emails found in mailbox: " << folder);
2155             break;
2156         } else if (EMAIL_ERROR_NONE != err) {
2157             LogError(
2158                 "Unable to get mail list for mailbox: " << folder <<
2159                 ", Error: " << err);
2160             Throw(WrtDeviceApis::Commons::PlatformException);
2161         }
2162
2163         // apply filter
2164         for (int i = 0; i < count; ++i) {
2165             Api::Messaging::IMessagePtr msg = MessageFactory::createMessage(EMAIL, results[i].mail_id);
2166
2167
2168             if (!filter
2169 //                      || filter->compare(MessageFactory::convertToEmail(msg))         //TODO implemnet compare in filter
2170                         ) {
2171                 retVal.push_back(msg);
2172             }
2173         }
2174
2175         startIndex += count;
2176     }
2177     while (count >= MESSAGE_FIND_LIMIT);
2178
2179     return retVal;
2180 }
2181
2182 vector<Api::Messaging::IMessagePtr> Messaging::findEmail(Api::Messaging::FolderType folder,
2183                 const Api::Tizen::FilterPtr& filter)
2184 {
2185     vector<Api::Messaging::IMessagePtr> result;
2186
2187     Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount();
2188     if (account.getId().empty()) {
2189         LogWarning("No valid email accounts.");
2190         return result;
2191     }
2192
2193     string name;
2194     try {
2195         name = EmailConverter::toMailboxName(folder);
2196     }
2197     catch (const WrtDeviceApis::Commons::PlatformException& ex) {
2198         LogWarning(ex.DumpToString());
2199         return result;
2200     }
2201
2202     int accountId = account.getIntId();
2203     int startIndex = 0;
2204     int count = 0;
2205     do {
2206         email_mail_list_item_t* messages = NULL;
2207         int error = email_get_mail_list(accountId,
2208                                            name.c_str(),
2209                                            EMAIL_LIST_TYPE_NORMAL,
2210                                            startIndex,
2211                                            MESSAGE_FIND_LIMIT,
2212                                            EMAIL_SORT_DATETIME_HIGH,
2213                                            &messages,
2214                                            &count);
2215         DPL::ScopedFree<email_mail_list_item_t> freeGuard(messages);
2216         if ((EMAIL_ERROR_MAIL_NOT_FOUND == error) || (NULL == messages)) {
2217             LogWarning("No emails found in mailbox: " << name);
2218             break;
2219         } else if (EMAIL_ERROR_NONE != error) {
2220             ThrowMsg(WrtDeviceApis::Commons::PlatformException,
2221                      "Couldn't get mail list from mailbox: " << name <<
2222                      ". [" << error << "]");
2223         }
2224
2225         for (int i = 0; i < count; ++i) {
2226             Api::Messaging::IMessagePtr msg =
2227                 MessageFactory::createMessage(EMAIL, messages[i].mail_id);
2228             if (!filter
2229 //                      ||filter->compare(MessageFactory::convertToEmail(msg))          //TODO implement compare in filter 
2230                 ) {
2231                 result.push_back(msg);
2232             }
2233         }
2234
2235         startIndex += count;
2236     }
2237     while (count >= MESSAGE_FIND_LIMIT);
2238
2239     return result;
2240 }
2241 */
2242 int Messaging::getConversationId(const int& msgId, const MessageType& msgtype)
2243 {
2244         LogDebug("Enter");
2245         
2246         switch(msgtype)
2247         {
2248                 case EMAIL:
2249                 {
2250                         int index = 0, count = 0;
2251 //                      char *mailBox = NULL;
2252                         email_mail_list_item_t *mailList = NULL;
2253                         email_mail_data_t* result = NULL;
2254                         
2255                         LogDebug("Current Account " << m_currentEmailAccountId);
2256
2257                         try 
2258                         {
2259                                 
2260                                 if (EMAIL_ERROR_NONE != email_get_mail_data(msgId, &result)) {
2261                                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
2262                                                          "Couldn't get conversatino Id " << msgId );
2263                                 }
2264
2265                                 if (email_get_mail_list(m_currentEmailAccountId, result->mailbox_id, EMAIL_LIST_TYPE_NORMAL, 0, MESSAGE_FIND_LIMIT, 
2266                                         EMAIL_SORT_DATETIME_HIGH, &mailList, &count) != EMAIL_ERROR_NONE)
2267                                 {
2268                                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "get email list fail" );
2269                                 }
2270
2271                                 email_free_mail_data(&result,1);
2272                                 
2273                                 for (index = 0; index < count; index++)
2274                                 {
2275                                         if (mailList[index].mail_id == (int)msgId)
2276                                         {
2277                                                 return mailList[index].thread_id;
2278                                         }
2279                                 }
2280                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException, "can not find msg" );
2281                         }
2282                         catch (const WrtDeviceApis::Commons::Exception& ex) 
2283                         {
2284 //                              if (mailBox)
2285 //                                      free(mailBox);
2286                                 email_free_mail_data(&result,1);
2287                                 LogError("Exception: " << ex.GetMessage());
2288                                 throw;  
2289                         }
2290                         return MSG_ERR_INVALID_MSG_TYPE;
2291                 }
2292                 break;
2293                 case SMS:
2294                 case MMS:
2295                 {
2296                         msg_struct_t msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
2297                         msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
2298                         msg_handle_t handle = MsgGetCommonHandle();
2299                         msg_error_t err = MSG_SUCCESS;
2300
2301                         err = msg_get_message(handle, msgId, msg, sendOpt);
2302
2303                         if( err < MSG_SUCCESS )
2304                         {
2305                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException,
2306                                 "can not find msg id(" << msgId << ")");
2307                         }
2308
2309                         int threadId = 0;
2310                         err = msg_get_int_value(msg, MSG_MESSAGE_THREAD_ID_INT, &threadId);
2311
2312                         LogDebug(err);
2313                         if( err < MSG_SUCCESS )
2314                         {
2315                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException,
2316                                 "can not find thread with msg id(" << msgId << ")");
2317                         }
2318
2319                         return threadId;
2320                 }
2321                 break;
2322                 default:
2323                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
2324                                 "Wrong Type (" << msgId << ")");
2325                         return MSG_ERR_INVALID_MSG_TYPE;
2326                 
2327         }
2328 }
2329 /*
2330 std::vector<Api::Messaging::IConversationPtr> Messaging::queryConversations(const Api::Tizen::SortModePtr& sortMode,
2331                 const Api::Tizen::FilterPtr& filter, long limit, long offset)
2332 {
2333         LogDebug("Enter");
2334
2335         std::vector<Api::Messaging::IConversationPtr> result;
2336         std::string filterSql;
2337         std::string orderLimitSql ="";  
2338
2339         ConversationQueryGeneratorPtr queryGenerator(new ConversationQueryGenerator(sortMode, limit, offset));
2340         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
2341         filter->travel(filterVisitor, 0);
2342
2343         LogDebug("filterSql:[" << filterSql <<"]");
2344
2345         int conversationType = queryGenerator->getMessageType();
2346         switch(conversationType){
2347                 case Api::Messaging::EMAIL:{
2348                         LogDebug("type is EMAIL:[" << conversationType <<"]");
2349                         queryGenerator->reset(MessageQueryGenerator::MODE_EMAIL);
2350                         filter->travel(filterVisitor, 0);
2351                         filterSql = queryGenerator->getQuery();
2352                         result = queryEmailConversation(filterSql);
2353                         break;
2354                 }
2355
2356                 case Api::Messaging::SMS:{
2357                         LogDebug("type is SMS:[" << conversationType <<"]");
2358                         queryGenerator->reset(MessageQueryGenerator::MODE_SMS_MMS);
2359                         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
2360                         filter->travel(filterVisitor, 0);
2361                         filterSql = queryGenerator->getQuery();
2362                         LogDebug("filterSql:[" << filterSql <<"]");
2363                         LogDebug("orderLimitSql:[" << orderLimitSql <<"]");
2364                         result = querySmsMmsConversation(filterSql, orderLimitSql);
2365                         break;
2366                 }
2367
2368                 case Api::Messaging::MMS:{
2369                         LogDebug("type is MMS:[" << conversationType <<"]");
2370                         queryGenerator->reset(MessageQueryGenerator::MODE_SMS_MMS);
2371                         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
2372                         filter->travel(filterVisitor, 0);
2373                         filterSql = queryGenerator->getQuery(); 
2374                         LogDebug("filterSql:[" << filterSql <<"]");
2375                         LogDebug("orderLimitSql:[" << orderLimitSql <<"]");
2376                         result = querySmsMmsConversation(filterSql, orderLimitSql);
2377                         break;
2378                 }
2379
2380                 default:{
2381                         LogError("[ERROR] >>> invlid type:[" << conversationType <<"]");
2382                  return result;
2383                 }
2384         }       //switch
2385
2386         return result;
2387 }
2388 */
2389 std::vector<Api::Messaging::IConversationPtr> Messaging::queryConversations(const Api::Tizen::FilterPtr& filter, 
2390                 const Api::Tizen::SortModePtr& sortMode, int type, long limit, long offset)
2391 {
2392         LogDebug("Enter");
2393
2394         std::vector<Api::Messaging::IConversationPtr> result;
2395         std::string filterSql;
2396         std::string orderLimitSql ="";
2397
2398         ConversationQueryGeneratorPtr queryGenerator(new ConversationQueryGenerator(sortMode, limit, offset, type));
2399         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
2400         filter->travel(filterVisitor, 0);
2401
2402         LogDebug("filterSql:[" << filterSql <<"]");
2403         int conversationType = queryGenerator->getMessageType();
2404         if(conversationType != -1)
2405         {
2406                 if(conversationType != type)
2407                 {
2408                         LogDebug("filter conversationType and service msg type is diff");               
2409                         ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "invalid Fiilter Type");
2410                 }
2411         }
2412         switch(type){
2413                 case Api::Messaging::EMAIL:{
2414                         LogDebug("type is EMAIL:[" << conversationType <<"]");
2415                         queryGenerator->reset(MessageQueryGenerator::MODE_EMAIL);
2416                         filter->travel(filterVisitor, 0);
2417                         filterSql = queryGenerator->getQuery();
2418                         result = queryEmailConversation(filterSql);
2419                         break;
2420                 }
2421
2422                 case Api::Messaging::SMS:{
2423                         LogDebug("type is SMS:[" << conversationType <<"]");
2424                         queryGenerator->reset(MessageQueryGenerator::MODE_SMS);
2425                         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
2426                         filter->travel(filterVisitor, 0);
2427                         filterSql = queryGenerator->getQuery();
2428                         orderLimitSql = queryGenerator->getOrderLimit();
2429                         LogDebug("filterSql:[" << filterSql <<"]");
2430                         LogDebug("orderLimitSql:[" << orderLimitSql <<"]");                     
2431                         result = querySmsMmsConversation(filterSql, orderLimitSql);
2432                         break;
2433                 }
2434
2435                 case Api::Messaging::MMS:{
2436                         LogDebug("type is MMS:[" << conversationType <<"]");
2437                         queryGenerator->reset(MessageQueryGenerator::MODE_MMS);
2438                         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
2439                         filter->travel(filterVisitor, 0);
2440                         filterSql = queryGenerator->getQuery();
2441                         orderLimitSql = queryGenerator->getOrderLimit();        
2442                         LogDebug("filterSql:[" << filterSql <<"]");
2443                         LogDebug("orderLimitSql:[" << orderLimitSql <<"]");
2444                         result = querySmsMmsConversation(filterSql, orderLimitSql);
2445                         break;
2446                 }
2447
2448                 default:{
2449                         LogError("[ERROR] >>> invlid type:[" << conversationType <<"]");
2450                  return result;
2451                 }
2452         }       //switch
2453
2454         return result;
2455 }
2456 /*
2457 bool Messaging::deleteConversations(const Api::Tizen::SortModePtr& sortMode, const Api::Tizen::FilterPtr& filter)
2458 {
2459         LogDebug("Enter");
2460
2461         std::vector<Api::Messaging::IConversationPtr> conversationsToDelete = queryConversations(sortMode, filter);
2462         return deleteConversations(conversationsToDelete);
2463 }
2464 */
2465 bool Messaging::deleteConversations(const std::vector<Api::Messaging::IConversationPtr>& conversations)
2466 {
2467         LogDebug("Enter");
2468
2469         if (conversations.size() == 0)
2470                 return false;
2471         
2472         if (conversations[0]->getType() == Api::Messaging::EMAIL)
2473         {
2474                 LogDebug("Enter-Email");
2475                 int threadId = 0;
2476
2477                 for (std::size_t i = 0; i < conversations.size(); ++i) 
2478                 {
2479                         threadId = conversations[i]->getId();
2480                         
2481                         if (email_delete_thread(threadId, false) != EMAIL_ERROR_NONE)
2482                         {
2483                                 return false;
2484                         }
2485                 }
2486         }
2487         else
2488         {
2489                 LogDebug("Enter-Msg");
2490                 msg_thread_id_t threadId = 0;
2491                 msg_handle_t handle = MsgGetCommonHandle();
2492                 
2493                 for (std::size_t i = 0; i < conversations.size(); ++i) 
2494                 {
2495                         threadId = conversations[i]->getId();
2496                         if (msg_delete_thread_message_list(handle, threadId) != MSG_SUCCESS)
2497                         {
2498                                 return false;
2499                         }
2500                 }
2501         }
2502         return true;
2503 }
2504
2505 std::vector<Api::Messaging::IMessageFolderPtr> Messaging::queryFolders(const Api::Tizen::FilterPtr& filter)
2506 {
2507         LogDebug("Enter");
2508
2509         email_mailbox_t* mailboxes = NULL;
2510         email_mailbox_t m_mailboxes;
2511         int mailboxesCount;
2512
2513         std::vector<Api::Messaging::IMessageFolderPtr> result;
2514         std::string folderName;
2515         int accountId = 0;
2516
2517     Api::Messaging::EmailAccountInfo account = getCurrentEmailAccount();
2518         
2519         if (account.getId().empty()) {
2520                 LogWarning("No valid email accounts. Skipping");
2521                 return result;
2522         }
2523
2524         const vector<Api::Messaging::EmailAccountInfo> accounts = getEmailAccounts();
2525
2526         FolderQueryGeneratorPtr queryGenerator(new FolderQueryGenerator());
2527         
2528         IFilterVisitorPtr filterVisitor = DPL::StaticPointerCast<IFilterVisitor>(queryGenerator);
2529         queryGenerator->reset();
2530         filter->travel(filterVisitor, 0);
2531         accountId = queryGenerator->getAccountId();
2532
2533         if(accountId == 0)
2534         {
2535                 LogWarning("No valid email accounts. accountId : 0");
2536                 return result;  
2537         }
2538
2539         if(queryGenerator->isFolderPathExist() == 1){
2540 /*              
2541                         folderName = queryGenerator->getFolderPath();
2542         
2543                 if(email_get_mailbox_by_name(accountId, folderName.c_str(), &mailboxes) != 1)
2544                 {
2545                         LogError("error during get mailboxes");         
2546                         return result;                          
2547                 }
2548
2549                 m_mailboxes = *mailboxes;                       
2550                 Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes));
2551                 result.push_back(folderPtr);
2552 */
2553         }else{
2554         if (!email_get_mailbox_list(accountId, -1, &mailboxes, &mailboxesCount) || !mailboxes) 
2555         {
2556                 LogError("error during get mailboxes");         
2557                 return result;          
2558         }
2559
2560         if (mailboxesCount <= 0)
2561         {
2562                 LogDebug("Empty...");
2563         }
2564         else 
2565         {
2566                 for (int i = 0; i < mailboxesCount; i++)
2567                 {
2568         
2569                         m_mailboxes = *mailboxes;                       
2570                         Api::Messaging::IMessageFolderPtr folderPtr(new MessageFolder(m_mailboxes));
2571                         result.push_back(folderPtr);
2572                         mailboxes++;                    
2573                 }
2574         }
2575         }
2576         return result;
2577
2578 }
2579
2580 }
2581 }
2582 }