Update change log and spec for wrt-plugins-tizen_0.2.73
[profile/ivi/wrt-plugins-tizen.git] / src / platform / Tizen / Messaging / Sms.cpp
1 /*
2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License. 
15 */
16
17
18 /**
19  *
20  *
21  * @file       Sms.cpp
22  * @author     Pawel Misiak (p.misiak@samsung.com)
23  * @version    0.1
24  * @brief
25  */
26 #include "Sms.h"
27 #include <dpl/log/log.h>
28 #include <Commons/Exception.h>
29 #include <API/Messaging/ReqReceiverMessage.h>
30 #include "Messaging.h"
31 #include "CallbackMgr.h"
32 #include "MsgServiceHandleMgr.h"
33
34 extern "C" {
35 #include <msg_storage.h>
36 }
37
38 using namespace std;
39 using namespace TizenApis::Api::Messaging;
40
41 namespace {
42 const char* EMPTY_ID = "0";
43 }
44
45 namespace TizenApis {
46 namespace Platform {
47 namespace Messaging {
48
49 Sms::Sms(const string& id) :
50     IMessage(SMS, id),
51     m_messageData(NULL)
52 {
53     LogDebug("enter");
54     LogDebug("m_id=" << getIdRef());
55     LogDebug("m_msgType=" << getMessageType());
56
57     if (getIdRef().empty()) {
58         createNewMessage();
59     } else {
60         readExistingMessage();
61     }
62
63     Touch();
64 }
65
66 Sms::Sms(const std::string& id, const msg_struct_t msg_data) :
67         IMessage(SMS, id),
68         m_messageData(msg_data)
69 {
70         LogDebug("enter");
71         LogDebug("m_id=" << getIdRef());
72         LogDebug("m_msgType=" << getMessageType());
73         readRecipientList(m_messageData);
74         readBody(m_messageData);
75         readFolder(m_messageData);
76         readDateTime(m_messageData);
77         readReadStatus(m_messageData);
78         readSize(m_messageData);
79         setMessageStatus(Api::Messaging::MESSAGE_STATUS_LOADED);
80
81         Touch();
82 }
83
84 Sms::~Sms()
85 {
86     LogDebug("enter");
87
88     if (m_messageData) {
89         // release platform message structure
90         msg_release_struct(&m_messageData);
91     }
92 }
93
94 void Sms::update(bool draftsOnly)
95 {
96     LogDebug("updating m_id=" << getIdRef());
97
98     if (!m_messageData) {
99         //error if platform message not exists
100         LogError("message can not be updated");
101         Throw(WrtDeviceApis::Commons::PlatformException);
102     }
103
104     //update all sms data
105     if (!draftsOnly || getCurrentFolder() == Api::Messaging::DRAFTBOX) {
106         updateBody();
107         updateFrom();
108         updateTo();
109         updateSourceAddress();
110     }
111     updateReadStatus();
112 }
113
114 void Sms::readAllData()
115 {
116     readExistingMessage();
117 }
118
119 void Sms::moveToFolder(const FolderType newFolder)
120 {
121 /*
122     update();
123
124     Try
125     {
126         const msg_folder_id_t platfromFolderId =
127             Messaging::convertFolderToPlatform(newFolder);
128
129         //call platform api to move message to other folder
130         if (msg_move_msg_to_folder(MsgGetCommonHandle(), convertId(getId()),
131                                    platfromFolderId) != MSG_SUCCESS) {
132             Throw(WrtDeviceApis::Commons::PlatformException);
133         }
134     }
135
136     Catch(WrtDeviceApis::Commons::PlatformException) {
137         LogError("remove message error");
138         throw;
139     }
140 */
141 }
142
143 void Sms::moveToFolder(const std::string& newFolder)
144 {
145 //    update();
146     //TODO
147 }
148
149 void Sms::copyToFolder(const FolderType newFolder)
150 {
151 /*
152     update();
153
154     msg_message_t msg = msg_new_message();
155
156     Try
157     {
158         MSG_SENDINGOPT_S option = { false, false, false };
159         option.option.smsSendOpt.bReplyPath = true;
160         // trying to get message from platform
161         if (MSG_SUCCESS ==
162             msg_get_message(MsgGetCommonHandle(), convertId(getIdRef()), msg,
163                             &option)) {
164             const msg_folder_id_t platfromFolderId =
165                 Messaging::convertFolderToPlatform(newFolder);
166             // new id will me set (initialize to 0)
167             msg_set_message_id(msg, 0);
168             msg_set_folder_id(msg, platfromFolderId);
169
170             // trying to add message
171             int error = msg_add_message(MsgGetCommonHandle(), msg, &option);
172             if (error != MSG_SUCCESS) {
173                 LogError("msg_add_message failed, error code=" << error);
174                 Throw(WrtDeviceApis::Commons::PlatformException);
175             }
176
177             //releasing platform message structure
178             msg_release_message(&msg);
179         }
180     }
181
182     Catch(WrtDeviceApis::Commons::PlatformException) {
183         LogError("remove message error");
184         if (msg) {
185             //releasing platform message structure
186             msg_release_message(&msg);
187         }
188         throw;
189     }
190 */
191 }
192
193 void Sms::copyToFolder(const std::string& newFolder)
194 {
195 //    update();
196     //TODO
197 }
198
199 int Sms::send()
200 {
201         LogDebug("sending message, id=" << getIdRef());
202         Try{
203                 if(m_messageData == NULL)
204                 {
205                         //prepare for sending sms
206                         update();
207                 }
208                 MsgGetCommonHandle();
209         }
210         Catch(WrtDeviceApis::Commons::PlatformException) 
211         {
212                 LogDebug("getHandle failed");
213                 Throw(WrtDeviceApis::Commons::PlatformException);
214         }
215
216     // split the message
217         SendRequest req;
218
219         msg_struct_list_s *addr_list = NULL;
220         msg_struct_list_s *new_addr_list = NULL;
221         char strNumber[MAX_ADDRESS_VAL_LEN] = {0,};
222         int nToCnt;
223         int tempInt;
224         int tempIdInt;
225
226         msg_get_list_handle(m_messageData, MSG_MESSAGE_ADDR_LIST_STRUCT, (void **)&addr_list);  
227         msg_get_int_value(m_messageData, MSG_MESSAGE_ID_INT, &tempIdInt);
228
229         nToCnt = addr_list->nCount;
230         LogDebug("nToCnt : " << nToCnt);
231
232         for (int i = 0; i < nToCnt; ++i) 
233         {
234                 msg_struct_t new_msg = createNewCopyOfPLatformMsg(m_messageData);
235                 msg_set_int_value(new_msg, MSG_MESSAGE_ID_INT, tempIdInt);
236
237                 msg_get_list_handle(new_msg, MSG_MESSAGE_ADDR_LIST_STRUCT, (void **)&new_addr_list);
238
239                 msg_get_int_value(addr_list->msg_struct_info[i], MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT, &tempInt);
240                 LogDebug("RECIPIENT_TYPE : " << tempInt);
241                 if(MSG_RECIPIENTS_TYPE_TO != tempInt) 
242                 {
243                         LogDebug("skip");
244                         continue;
245                 }
246
247                 msg_get_str_value(addr_list->msg_struct_info[i], MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, MAX_ADDRESS_VAL_LEN);
248                 msg_set_str_value(new_addr_list->msg_struct_info[0], MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, MAX_ADDRESS_VAL_LEN);
249                 msg_set_int_value(new_addr_list->msg_struct_info[0], MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT, MSG_RECIPIENTS_TYPE_TO);              
250                 new_addr_list->nCount = 1;
251
252                 setMessageStatus(MESSAGE_STATUS_SENDING);
253
254                 req.queue.push(new_msg);                
255         }
256
257
258         DPL::Mutex::ScopedLock lock(&m_mutex);
259         m_sendRequests.push(req);
260
261     // schedule sending
262         PostEvent(0);
263
264         LogDebug("sending method finished");
265
266         return 0;               //sms handle is -1;
267 }
268
269 void Sms::sendingCallback(msg_struct_t sent_status)
270 {
271 //    LogInfo(
272 //        "sendingCallback callback received. Req id = " <<
273 //        sent_status->reqId << " Status = " << (int)sent_status->status <<
274 //        ", Recipient=" << getRecipient());
275     int status = MSG_NETWORK_SEND_FAIL;
276
277     msg_get_int_value(sent_status, MSG_SENT_STATUS_NETWORK_STATUS_INT, &status);
278
279     DPL::Mutex::ScopedLock lock(&m_mutex);
280
281     if (status != MSG_NETWORK_SEND_SUCCESS) {
282         m_sendRequests.front().failed = true; // TODO mutex
283         //send callback, error for recipient
284         setSendingStatusFailed(getRecipient());
285         setMessageStatus(MESSAGE_STATUS_FAILED);
286     } else {
287         setSendingStatusOk(getRecipient());
288         setMessageStatus(MESSAGE_STATUS_SENT);
289     }
290         
291     msg_release_struct(&currentQueue().front());
292     currentQueue().pop();
293
294     //schedule another sub message send
295     PostEvent(0);
296 }
297
298 void Sms::OnEventReceived(const int&)
299 {
300     LogDebug("enter");
301     // send another one
302     sendSubMessage();
303 }
304
305 Api::Messaging::FolderType Sms::toFolder(const std::string &folder)
306 {
307     if (folder == "INBOX") {
308         return INBOX;
309     } else if (folder == "OUTBOX") {
310         return OUTBOX;
311     } else if (folder == "SENTBOX") {
312         return SENTBOX;
313     } else if (folder == "DRAFTBOX") {
314         return DRAFTBOX;
315     }
316     ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Invalid folder");
317 }
318
319 void Sms::sendSubMessage()
320 {
321     LogDebug("enter");
322
323     DPL::Mutex::ScopedLock lock(&m_mutex);
324
325     // if current request queue gets empty, try next one
326     while (!m_sendRequests.empty()) {
327         // send as long as the sending fails until there are no more messages
328         for (msg_error_t err = MSG_ERR_UNKNOWN;
329              err != MSG_SUCCESS && !currentQueue().empty(); ) 
330         {
331             err = CallbackMgrSingleton::Instance().registerAndSend(
332                     msg_sms_send_message,
333                     currentQueue().front(),
334                     this);
335             LogInfo("Sending Message (submit request) result:" << err);
336             if (err != MSG_SUCCESS) {
337                 LogError("Sending Message (submit request) failed!!! err=" << err);
338                 msg_release_struct(&currentQueue().front());
339                 currentQueue().pop();
340                 m_sendRequests.front().failed = true;
341                 //send callback, error for recipient
342                 setSendingStatusFailed(getRecipient());
343             }
344         }
345
346         // empty queue -> notify about results
347         if (currentQueue().empty()) {
348                 /*
349             if (m_sendRequests.front().failed) {
350                 setSendingStatusFailed();
351             } else {
352                 setSendingStatusOk();
353             }
354             */
355             // this request is finished, try next one
356             m_sendRequests.pop();
357             continue;
358         }
359         break;
360     }
361 }
362
363 void Sms::setSendingStatusOk(const string &recipient)
364 {
365     LogDebug("enter, success number is : " << recipient);
366     //success callback should be executed here
367     ReqReceiverMessage *requestReceiver = getRequestReceiver();
368     if (requestReceiver) {
369          EventMessagingServicePtr event = getMessagingServiceEvent();
370          event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::None);
371          event->m_successRecipients.push_back(recipient);
372
373          msg_struct_list_s *addr_list = NULL;    
374          msg_get_list_handle(m_messageData, MSG_MESSAGE_ADDR_LIST_STRUCT, (void **)&addr_list);
375          
376           if ( event->m_successRecipients.size() + event->m_failRecipients.size() == (unsigned int)addr_list->nCount)
377         {
378                 requestReceiver->WrtDeviceApis::Commons::EventRequestReceiver< EventMessagingService >::ManualAnswer(event);
379         }
380          
381 #if 0
382         EventSendMessagePtr event = getSendMessageEvent();
383         event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::None);
384         event->m_successRecipients.push_back(recipient);
385           //LogDebug("total address size : " << msg_get_address_count(m_messageData) << " Status size : " << event->m_successRecipients.size() + event->m_failRecipients.size());
386         if ( event->m_successRecipients.size() + event->m_failRecipients.size() == (unsigned int)msg_get_address_count(m_messageData))
387         {
388                 requestReceiver->WrtDeviceApis::Commons::EventRequestReceiver< EventSendMessage >::ManualAnswer(event);
389         }
390 #endif
391                 
392     }
393 }
394
395 void Sms::setSendingStatusFailed(const string &recipient)
396 {
397     LogDebug("enter, fail number is : " << recipient);
398     //error callback should be executed here
399     EventOnSendingFailedEmitterPtr emitter = getEmitter();
400     if (emitter) {
401         EventOnSendingFailedPtr event(new EventOnSendingFailed);
402         event->setError(EventOnSendingFailed::UNKNOWN); // TODO error codes
403         emitter->emit(event);
404     } else {
405         ReqReceiverMessage *requestReceiver = getRequestReceiver();
406         if (requestReceiver) {
407             LogError("calling JS error callback");
408             EventMessagingServicePtr event = getMessagingServiceEvent();
409             event->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::UnknownException);
410                 event->m_successRecipients.push_back(recipient);
411                 msg_struct_list_s *addr_list = NULL;    
412                 msg_get_list_handle(m_messageData, MSG_MESSAGE_ADDR_LIST_STRUCT, (void **)&addr_list);
413                 
414                  if ( event->m_successRecipients.size() + event->m_failRecipients.size() == (unsigned int)addr_list->nCount)
415                  {
416                    requestReceiver->WrtDeviceApis::Commons::EventRequestReceiver< EventMessagingService >::ManualAnswer(event);
417                  }
418
419         }
420     }
421 }
422
423 void Sms::remove()
424 {
425     Try
426     {
427         // delete message from platform
428         if (msg_delete_message(MsgGetCommonHandle(),
429                                convertId(getId())) != MSG_SUCCESS) {
430             LogError("delete message failed");
431             Throw(WrtDeviceApis::Commons::PlatformException);
432         } else {
433             LogDebug("message deleted succesfully");
434         }
435     }
436
437     Catch(WrtDeviceApis::Commons::PlatformException) {
438         LogError("remove message error");
439         throw;
440     }
441 }
442
443 void Sms::createNewMessage()
444 {
445     LogDebug("enter");
446     if (m_messageData) {
447         // release platform message if it was created previously
448         msg_release_struct(&m_messageData);
449         m_messageData = NULL;
450     }
451     // create new platform message
452     LogDebug("create messeage instance");
453     m_messageData = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
454     LogDebug("created message : " << m_messageData);
455         
456     Try
457     {
458         //default message initialization
459         // update sms data
460         updateBody();
461         updateTo();
462
463         setMessageStatus(Api::Messaging::MESSAGE_STATUS_DRAFT);
464
465         tm dateT = getDateTime();
466         msg_set_int_value(m_messageData, MSG_MESSAGE_DISPLAY_TIME_INT, (int)mktime(&dateT));
467
468           setMessageStatus(Api::Messaging::MESSAGE_STATUS_CREATED);
469         LogDebug("Message created successfully, msgId=" << getId());
470     }
471     Catch(WrtDeviceApis::Commons::PlatformException) {
472         msg_release_struct(&m_messageData);
473         LogError("Problem with message creation, cleaning");
474     }
475 }
476
477 void Sms::readExistingMessage()
478 {
479         if (getIdRef().empty() || (EMPTY_ID == getIdRef())) {
480                 ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Empty id.");
481         }
482
483         // release old data
484         msg_release_struct(&m_messageData);
485         m_messageData = NULL;
486         msg_struct_t sendOpt = NULL;
487
488         Try {
489                 // create new platform structure
490                 m_messageData = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
491                 sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
492
493                 msg_message_id_t l_id = convertId(getIdRef());
494                 LogDebug("reading message id=" << l_id);
495                 // trying to get message from platform
496                 if (MSG_SUCCESS == msg_get_message(MsgGetCommonHandle(), l_id, m_messageData, sendOpt)) 
497                 {
498                         LogDebug("message found with msgId=" << getIdRef());
499
500                         // read all mms dat to abstraction layer
501                         readRecipientList(m_messageData);
502                         readBody(m_messageData);
503                         readFolder(m_messageData);
504                         readDateTime(m_messageData);
505                         readReadStatus(m_messageData);
506                         readSize(m_messageData);
507                         setMessageStatus(Api::Messaging::MESSAGE_STATUS_LOADED);
508
509                 } else {
510                         LogError("message not found with msgId=" << getIdRef());
511                         setId("");
512                         Throw(WrtDeviceApis::Commons::PlatformException);
513                 }
514
515                 msg_release_struct(&sendOpt);
516         }
517         Catch(WrtDeviceApis::Commons::PlatformException) {
518                 LogError("exception");
519                 // nothing to do
520                 msg_release_struct(&sendOpt);
521         }
522 }
523
524 void Sms::updateBody()
525 {
526     // check if abstraction body value has been changed
527     if (isBodyValid()) {
528         return;
529     }
530     LogInfo("updating platfoprm body");
531
532     // change body value in platform structure
533     if (  getBodyRef().length() >  0)
534     {
535                 if (msg_set_str_value(m_messageData, MSG_MESSAGE_SMS_DATA_STR, 
536                         const_cast<char*>(getBodyRef().c_str()), getBodyRef().length()) != MSG_SUCCESS)
537                 {
538         LogError("problem with update Body");
539         Throw(WrtDeviceApis::Commons::PlatformException);
540         }
541     // set flag as true - platform synchronized with abstraction
542     setBodyValidity(true);
543 }
544     // set flag as true - platform synchronized with abstraction
545 }
546
547 void Sms::updateTo()
548 {
549         // check if abstraction recipient value has been changed
550     if (getToRecipients().isValid()) {
551         return;
552     }
553
554         LogInfo("SMS updating platform recipients");
555
556         // reset addresses in platform structure
557 //        msg_reset_address(m_messageData);
558         msg_struct_list_s *addr_list = NULL;
559         msg_get_list_handle(m_messageData, MSG_MESSAGE_ADDR_LIST_STRUCT, (void **)&addr_list);
560         int nToCnt = addr_list->nCount;
561
562         LogInfo("nToCnt size  " << nToCnt);
563         
564         if (nToCnt > 0)         
565         {               
566                 for (int i = 0; i < nToCnt; i++) {      
567                         msg_set_str_value(addr_list->msg_struct_info[i], MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, "", 0);
568                         msg_set_str_value(addr_list->msg_struct_info[i], MSG_ADDRESS_INFO_DISPLAYNAME_STR, "", 0);
569                         msg_set_int_value(addr_list->msg_struct_info[i], MSG_ADDRESS_INFO_ADDRESS_TYPE_INT, MSG_ADDRESS_TYPE_PLMN);
570                         msg_set_int_value(addr_list->msg_struct_info[i], MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT, MSG_RECIPIENTS_TYPE_UNKNOWN);
571                         msg_set_int_value(addr_list->msg_struct_info[i], MSG_ADDRESS_INFO_CONTACT_ID_INT, 0);
572                 }
573                 nToCnt = 0;
574                 addr_list->nCount = nToCnt;
575         }
576
577     vector<string> to = getToRecipients().getRecipients();
578         // update addresses in platform structure
579         if (to.size()) 
580         {
581     LogInfo("updating to");
582                 for (size_t i = 0; i < to.size(); i++) 
583                 {
584                         string tmpAddr = to[i];
585                         if(validatePhoneNumber(tmpAddr))
586                         {
587                                 if (i >= MAX_TO_ADDRESS_CNT) 
588                                 {
589             LogError("max number of recipient exceeded");
590             break;
591         }
592         LogDebug("adding to[" << i << "]=" << to[i]);
593                                 
594                                 if (msg_set_int_value(addr_list->msg_struct_info[i], MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT, 
595                                         MSG_RECIPIENTS_TYPE_TO) != MSG_SUCCESS) 
596                                 {
597                                         LogError("problem with adding to address");
598                                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Problem with adding to address");
599                                 }
600
601                                 if(msg_set_str_value(addr_list->msg_struct_info[i], MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, 
602                                         const_cast<char*>(to[i].c_str()), to[i].size()) != MSG_SUCCESS) 
603                                 {
604                                         LogError("problem with adding to address");
605                                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Problem with adding to address");
606                                 }
607
608                                 addr_list->nCount ++;
609                                 LogDebug("addr_list->nCount =" << addr_list->nCount);
610             }
611                         else
612                         {
613             LogError("wrong phone number format");
614                         }
615         }
616     }
617
618     setToValidity(true);
619         
620 }
621
622 void Sms::updateFrom()
623 {
624     // check if abstraction from field value has been changed
625     if (getFromValidity()) {
626         // do not update if not changed
627         return;
628     }
629     LogInfo("updating platform from");
630
631     //TODO
632
633     // set flag as true - platform synchronized with abstraction
634     setFromValidity(true);
635 }
636
637 void Sms::updateSourceAddress()
638 {
639     // check if abstraction source address value has been changed
640     if (getSourceAddressValidity()) {
641         // do not update if not changed
642         return;
643     }
644     LogInfo("updating platform source address");
645
646     //TODO
647
648     // set flag as true - platform synchronized with abstraction
649     setSourceAddressValidity(true);
650 }
651
652 void Sms::updateReadStatus()
653 {
654     LogInfo("updating platform read status: " << isRead());
655     if (isReadStatusValid()) {
656         // do not update if not changed
657         return;
658     }
659     if (MSG_SUCCESS != msg_set_bool_value(m_messageData, MSG_MESSAGE_READ_BOOL, isRead())) {
660         LogError("problem with setting subject");
661         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Problem with setting subject");
662     }
663     setReadStatusValidity(true);
664 }
665
666 void Sms::updateIsRead()
667 {
668     LogDebug("updating m_id=" << getIdRef());
669
670     if (!m_messageData) {
671         //error if platform message not exists
672         LogError("message can not be updated");
673         Throw(WrtDeviceApis::Commons::PlatformException);
674     }
675         
676     // check if abstraction from m_isReadChange value has been changed
677     if (isReadChangeStatusValid()) {
678         // do not update if not changed
679         return;
680     }
681         
682     Try
683     {
684         if (this->getIdRef().empty()) {
685             LogError("existing msgId is zero, remove msg not done");
686             ThrowMsg(WrtDeviceApis::Commons::PlatformException,
687                     "existing msgId is zero, remove msg not done");
688         }
689
690         if (MSG_SUCCESS !=
691             msg_update_read_status(MsgGetCommonHandle(), convertId(getIdRef()), isReadChangeStatus()))
692         {
693             LogError("Failed to update isRead");
694             ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Failed to update isRead");
695         }
696     }
697     Catch(WrtDeviceApis::Commons::PlatformException) {
698         LogError("platform error occurs");
699     }
700     setisReadChangeStatusValidity(true);
701         
702 }
703
704 void Sms::updateMessage()
705 {
706         LogDebug("updating m_id=" << getIdRef());
707         msg_error_t err = MSG_SUCCESS;
708         
709         msg_struct_t msg = NULL;
710         msg_struct_t sendOpt = NULL;
711         
712         if (!m_messageData) {
713                 //error if platform message not exists
714                 LogError("message can not be updated");
715                 Throw(WrtDeviceApis::Commons::PlatformException);
716         }
717         
718         Try
719         {
720
721                 msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
722                 sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
723                 
724                 err = msg_get_message(MsgGetCommonHandle(), convertId(getIdRef()), msg, sendOpt);
725                 
726                 if (err != MSG_SUCCESS)
727                 {
728                         LogError("Get Message Failed!");
729                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Failed to update message");
730                 }
731         
732                 if (this->getIdRef().empty()) {
733                         LogError("existing msgId is zero, update msg not done");
734                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
735                                         "existing msgId is zero, update msg not done");
736                 }
737                 
738                 update(TRUE);
739                 
740                 if (MSG_SUCCESS != msg_update_message(MsgGetCommonHandle(), m_messageData, sendOpt))
741                 {
742                         LogError("Failed to update message");
743                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Failed to update message");
744                 }
745                 msg_release_struct(&msg);
746                 msg_release_struct(&sendOpt);
747         }
748         Catch(WrtDeviceApis::Commons::PlatformException) {
749                 msg_release_struct(&msg);
750                 msg_release_struct(&sendOpt);
751                 LogError("platform error occurs");
752         }
753 }
754
755 void Sms::createSendMessage()
756 {
757         LogDebug("convert m_id= " << convertId(getIdRef()));    
758
759         //prepare for add sms to draft folder
760         if (!m_messageData) {
761                 //error if platform message not exists
762                 LogError("message can not be updated");
763                 Throw(WrtDeviceApis::Commons::PlatformException);
764         }
765
766         //update all sms data
767         if (getCurrentFolder() == Api::Messaging::DRAFTBOX) {
768                 LogDebug("update all sms data");
769                 updateBody();
770                 updateFrom();
771                 updateTo();
772                 updateSourceAddress();
773         }
774
775         Try
776         {
777                 int msgId = 0;
778 //              MSG_SENDINGOPT_S option = { false, false, false };
779 //              option.option.smsSendOpt.bReplyPath = true;
780                 // trying to get message from platform
781
782 //              const msg_folder_id_t platfromFolderId = Messaging::convertFolderToPlatform(DRAFTBOX);
783
784 //              msg_set_message_id(m_messageData, msgId);               
785 //              msg_set_folder_id(m_messageData, platfromFolderId);
786 //              msg_set_network_status(m_messageData, MSG_NETWORK_NOT_SEND);
787
788                 setId(convertId(msgId));
789                 setFolderType(Api::Messaging::DRAFTBOX);
790                 setMessageStatus(Api::Messaging::MESSAGE_STATUS_DRAFT);
791         }
792         Catch(WrtDeviceApis::Commons::PlatformException) {
793                 LogError("remove message error");
794                 if (m_messageData) {
795                         //releasing platform message structure
796                         msg_release_struct(&m_messageData);
797                 }
798                 throw;
799         }
800
801 }
802
803
804
805 void Sms::addMessageToDraft()
806 {
807     LogDebug("convert m_id= " << convertId(getIdRef()));        
808     msg_struct_t sendOpt = NULL;
809
810     //prepare for add sms to draft folder
811     if (!m_messageData) {
812         //error if platform message not exists
813         LogError("message can not be updated");
814         Throw(WrtDeviceApis::Commons::PlatformException);
815     }
816
817     //update all sms data
818     if (getCurrentFolder() == Api::Messaging::DRAFTBOX) {
819         LogDebug("update all sms data");
820         updateBody();
821         updateFrom();
822         updateTo();
823         updateSourceAddress();
824     }
825
826     Try
827     {
828         sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
829         msg_set_bool_value(sendOpt, MSG_SEND_OPT_SETTING_BOOL, false);
830         int msgId = -1;
831 //        MSG_SENDINGOPT_S option = { false, false, false };
832 //        option.option.smsSendOpt.bReplyPath = true;
833         // trying to get message from platform
834
835 //        const msg_folder_id_t platfromFolderId = Messaging::convertFolderToPlatform(DRAFTBOX);
836
837 //        msg_set_message_id(m_messageData, 0);         
838 //        msg_set_folder_id(m_messageData, platfromFolderId);
839 //        msg_set_network_status(m_messageData, MSG_NETWORK_NOT_SEND);
840
841         // trying to add message
842         int ret = msg_add_message(MsgGetCommonHandle(), m_messageData, sendOpt);
843         if (ret < MSG_SUCCESS) {
844             LogError("msg_add_message failed, error code=" << ret);
845             Throw(WrtDeviceApis::Commons::PlatformException);
846         }
847         else
848         {
849                 msgId = ret;    
850         }
851                         
852           LogDebug("Message ID : " << msgId);
853           if (msgId < 0)
854           {
855                  LogDebug("Message ID is invailded ");
856                  Throw(WrtDeviceApis::Commons::PlatformException);
857           }
858           
859           msg_set_int_value(m_messageData, MSG_MESSAGE_ID_INT, msgId);
860
861           setId(convertId(msgId));
862         setFolderType(Api::Messaging::DRAFTBOX);
863         setMessageStatus(Api::Messaging::MESSAGE_STATUS_DRAFT);
864           LogDebug("Message Status " <<  getMessageStatus());
865
866 #if 0
867           if ( folder_list_view.nCount )
868                 msg_release_list_struct(&folder_list_view);
869 #endif    
870         msg_release_struct(&sendOpt);
871
872     }
873     Catch(WrtDeviceApis::Commons::PlatformException) {
874         LogError("remove message error");
875         if (m_messageData) {
876             //releasing platform message structure
877             msg_release_struct(&m_messageData);
878             msg_release_struct(&sendOpt);
879         }
880         throw;
881     }
882
883 }
884
885 void Sms::readRecipientList(msg_struct_t& messageData)
886 {
887         std::string phoneNumber;
888 //      int recipientCount = msg_get_address_count(messageData);
889 //      LogDebug("Recipient count " << recipientCount);
890
891         msg_struct_list_s *addr_list;
892         msg_get_list_handle(messageData, MSG_MESSAGE_ADDR_LIST_STRUCT, (void **)&addr_list);
893
894         int tempInt = 0;
895         char strNumber[MAX_ADDRESS_VAL_LEN] = {0,};
896
897         int recipientCount = addr_list->nCount;
898         LogDebug("Recipient count " << recipientCount);
899
900         
901         for (int i = 0; i < recipientCount; ++i) 
902 {
903                 msg_get_int_value(messageData, MSG_MESSAGE_DIRECTION_INT, &tempInt);
904                 int type = tempInt;
905
906                 if (MSG_DIRECTION_TYPE_MT == type) 
907                 {
908                         msg_struct_t addr_info = addr_list->msg_struct_info[i];
909                         msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, MAX_ADDRESS_VAL_LEN);
910                         phoneNumber = strNumber;
911                 
912                         if (validatePhoneNumber(phoneNumber)) 
913                         {
914                                 setSourceAddress(phoneNumber);
915                                 setFrom(phoneNumber);
916                         }
917                         LogDebug("MT number: " << phoneNumber);
918             }
919                 else if (MSG_DIRECTION_TYPE_MO == type) 
920                 {
921                         msg_struct_t addr_info = addr_list->msg_struct_info[i];
922                         msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, MAX_ADDRESS_VAL_LEN);
923                         LogDebug("MO number: " << strNumber);
924                         appendToRecipients(strNumber);
925                 } 
926                 else 
927                 {
928                         LogError("Wrong type of recipient");
929                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Wrong type of recipient");
930         }
931     }
932 }
933
934 void Sms::readBody(msg_struct_t& messageData)
935 {
936     //set abstraction body value
937     int tempInt;
938     msg_get_int_value(messageData, MSG_MESSAGE_DATA_SIZE_INT, &tempInt);
939     LogError("body Size : " <<tempInt);
940     char msgText[tempInt+1];
941     memset(msgText, 0, tempInt+1);
942     msg_get_str_value(messageData, MSG_MESSAGE_SMS_DATA_STR, msgText, tempInt);
943 //    setBody(msg_sms_get_message_body(messageData));
944     LogError("body : " <<msgText);
945     setBody(msgText);
946 }
947
948 void Sms::readFolder(msg_struct_t& messageData)
949 {
950     int tempInt = 0;
951     msg_get_int_value(messageData, MSG_MESSAGE_FOLDER_ID_INT, &tempInt);
952     LogError("Folder : " <<tempInt);
953
954     switch (tempInt) {
955     case MSG_INBOX_ID:
956         setFolderType(Api::Messaging::INBOX);
957         break;
958     case MSG_OUTBOX_ID:
959         setFolderType(Api::Messaging::OUTBOX);
960         break;
961     case MSG_SENTBOX_ID:
962         setFolderType(Api::Messaging::SENTBOX);
963         break;
964     case MSG_DRAFT_ID:
965         setFolderType(Api::Messaging::DRAFTBOX);
966         break;
967     default:
968         LogError("Wrong folder id");
969         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Unsupported folder id.");
970     }
971 }
972
973 void Sms::readDateTime(msg_struct_t& messageData)
974 {
975 //  tm* time = localtime(msg_get_time(messageData));
976 //    tm dateT = getDateTime();
977     int tempInt = 0;
978     msg_get_int_value(messageData, MSG_MESSAGE_DISPLAY_TIME_INT, &tempInt);
979
980     LogError("readDateTime : " <<tempInt);
981
982     tm* time = localtime((time_t*)&tempInt);
983     if (!time) {
984         LogError("localtime failed");
985         Throw(WrtDeviceApis::Commons::PlatformException);
986     }
987     setDateTime(*time);
988 }
989
990 void Sms::readReadStatus(msg_struct_t& messageData)
991 {
992     // get read status
993     bool tempBool = 0;
994     msg_get_bool_value(messageData, MSG_MESSAGE_READ_BOOL, &tempBool);
995     LogError("readReadStatus : " <<tempBool);
996     setReadStatus(tempBool);
997 }
998
999 void Sms::readSize(msg_struct_t& messageData)
1000 {
1001     int tempInt;
1002     msg_get_int_value(messageData, MSG_MESSAGE_DATA_SIZE_INT, &tempInt);
1003 //    setSize(msg_get_message_body_size(messageData));
1004     LogError("readSize : " <<tempInt);
1005     setSize(tempInt);
1006 }
1007
1008 msg_struct_t Sms::createNewCopyOfPLatformMsg(const msg_struct_t src) const
1009 {
1010         int tempInt;
1011         bool tempBool;
1012         
1013         msg_struct_t msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
1014
1015         msg_get_int_value(src, MSG_MESSAGE_STORAGE_ID_INT, &tempInt);
1016         msg_set_int_value(msg, MSG_MESSAGE_STORAGE_ID_INT, tempInt);
1017
1018         msg_get_int_value(src, MSG_MESSAGE_FOLDER_ID_INT, &tempInt);
1019         msg_set_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, tempInt);
1020
1021         msg_get_int_value(src, MSG_MESSAGE_DATA_SIZE_INT, &tempInt);
1022         char tempStr[tempInt+1];
1023         memset(tempStr, 0, tempInt+1);
1024
1025         msg_get_str_value(src, MSG_MESSAGE_SMS_DATA_STR, tempStr, tempInt);
1026         msg_set_str_value(msg, MSG_MESSAGE_SMS_DATA_STR, tempStr, strlen(tempStr));
1027
1028         msg_get_int_value(src, MSG_MESSAGE_DISPLAY_TIME_INT, &tempInt);
1029         msg_set_int_value(msg, MSG_MESSAGE_DISPLAY_TIME_INT, tempInt);
1030
1031 //    msg_set_network_status(msg, msg_get_network_status(src));
1032         msg_get_int_value(src, MSG_MESSAGE_NETWORK_STATUS_INT, &tempInt);
1033         msg_set_int_value(msg, MSG_MESSAGE_NETWORK_STATUS_INT,  tempInt);
1034
1035 //    msg_set_encode_type(msg, msg_get_encode_type(src));
1036         msg_get_int_value(src, MSG_MESSAGE_ENCODE_TYPE_INT, &tempInt);
1037         msg_set_int_value(msg, MSG_MESSAGE_ENCODE_TYPE_INT,  tempInt);
1038
1039 //    msg_set_read_status(msg, msg_is_read(src));
1040         msg_get_bool_value(src, MSG_MESSAGE_READ_BOOL, &tempBool);
1041         msg_set_bool_value(msg, MSG_MESSAGE_READ_BOOL, tempBool);
1042
1043 //        msg_set_protect_status(msg, msg_is_protected(src));
1044         msg_get_bool_value(src, MSG_MESSAGE_PROTECTED_BOOL, &tempBool);
1045         msg_set_bool_value(msg, MSG_MESSAGE_PROTECTED_BOOL, tempBool);
1046
1047 //        msg_set_priority_info(msg, msg_get_priority_info(src));
1048         msg_get_int_value(src, MSG_MESSAGE_PRIORITY_INT, &tempInt);
1049         msg_set_int_value(msg, MSG_MESSAGE_PRIORITY_INT,  tempInt);
1050
1051 //        msg_set_direction_info(msg, msg_get_direction_info(src));
1052         msg_get_int_value(src, MSG_MESSAGE_DIRECTION_INT, &tempInt);
1053         msg_set_int_value(msg, MSG_MESSAGE_DIRECTION_INT,  tempInt);
1054
1055 //        msg_set_port(msg, msg_get_dest_port(src), msg_get_src_port(src));
1056         msg_get_int_value(src, MSG_MESSAGE_DEST_PORT_INT, &tempInt);
1057         msg_set_int_value(msg, MSG_MESSAGE_DEST_PORT_INT,  tempInt);
1058         msg_get_int_value(src, MSG_MESSAGE_SRC_PORT_INT, &tempInt);
1059         msg_set_int_value(msg, MSG_MESSAGE_SRC_PORT_INT,  tempInt);
1060
1061     return msg;
1062 }
1063 }
1064 }
1065 }