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