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