8e9c16be6613d3470b038e549055f017bf47be9f
[profile/ivi/wrt-plugins-tizen.git] / src / platform / Tizen / Contact / ContactSearchEngine.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  * @file        ContactSearchEngine.cpp
19  * @author      Kisub Song (kisubs.song@samsung.com)
20  * @version     0.1
21  * @brief
22  */
23
24 #include "query-svc/query-service.h"
25 #include "time.h"
26
27 #include <iomanip>
28 #include <Commons/Exception.h>
29 #include "Contact.h"
30 #include "ContactSearchEngine.h"
31
32 namespace TizenApis {
33 namespace Platform {
34 namespace Contact {
35
36 using namespace TizenApis::Api::Contact;
37 using namespace TizenApis::Api::Tizen;
38 using namespace WrtDeviceApis::Commons;
39 using namespace std;
40
41 map<string, int> ContactSearchEngine::attrEnumMap = {
42                 {"id",                                          contact_attribute_e::CONTACT_ID},
43                 {"readOnly",                            contact_attribute_e::ATTRIBUTE_MAX},
44                 {"accountId",                           contact_attribute_e::ATTRIBUTE_MAX},
45                 {"prefix",                                      contact_attribute_e::NAME_PREFIX},
46                 {"name.firstName",                      contact_attribute_e::NAME_FIRST},
47                 {"name.middleName",                     contact_attribute_e::NAME_MIDDLE},
48                 {"name.lastName",                       contact_attribute_e::NAME_LAST},
49                 {"name.nicknames",                      contact_attribute_e::NICKNAME_NAME},
50                 {"name.phoneticName",           contact_attribute_e::NAME_PHONETIC},
51                 {"name.displayName",            contact_attribute_e::NAME_DISPLAY},
52                 {"addresses.country",           contact_attribute_e::ADDRESS_COUNTRY},
53                 {"addresses.region",            contact_attribute_e::ADDRESS_REGION},
54                 {"addresses.city",                      contact_attribute_e::ADDRESS_CITY},
55                 {"addresses.streetAddress",     contact_attribute_e::ADDRESS_STREET},
56                 {"addresses.additionalInformation",             contact_attribute_e::ADDRESS_ADDITIONAL},
57                 {"addresses.postalCode",        contact_attribute_e::ADDRESS_POSTAL_CODE},
58                 {"addresses.types",                     contact_attribute_e::ATTRIBUTE_MAX},
59                 {"photoURI",                            contact_attribute_e::CONTACT_PHOTO_URI},
60                 {"phoneNumbers.number",         contact_attribute_e::NUMBER_ADDRESS},
61                 {"phoneNumbers.types",          contact_attribute_e::NUMBER_TYPES},
62                 {"emails.email",                        contact_attribute_e::EMAIL_ADDRESS},
63                 {"emails.types",                        contact_attribute_e::EMAIL_TYPE},
64                 {"birthday",                            contact_attribute_e::EVENT_DATE},
65                 {"anniversaries.date",          contact_attribute_e::EVENT_DATE},
66                 {"organizations.name",          contact_attribute_e::ORGANIZATION_NAME},
67                 {"organization.department",             contact_attribute_e::ORGANIZATION_DEPARTMENT},
68                 {"organization.title",          contact_attribute_e::ORGANIZATION_TITLE},
69                 {"organization.role",           contact_attribute_e::ORGANIZATION_ROLE},
70                 {"organization.logoURI",        contact_attribute_e::ATTRIBUTE_MAX},
71                 {"notes",                                       contact_attribute_e::CONTACT_NOTE},
72                 {"urls.url",                            contact_attribute_e::URL_ADDRESS},
73                 {"urls.type",                           contact_attribute_e::URL_TYPE},
74                 {"lastUpdated",                         contact_attribute_e::CONTACT_LAST_UPDATED_TIME_STAMP},
75                 {"isFavorite",                          contact_attribute_e::CONTACT_IS_FAVORITE},
76                 {"ringtoneURI",                         contact_attribute_e::CONTACT_RINGTONE},
77                 {"categories",                          contact_attribute_e::CATEGORY_INFO}
78 };
79
80
81 ContactSearchEngine::ContactSearchEngine(ContactQueryType type)
82 {
83         query_error error;
84         query_type_e qtype = query_type_e::QUERY_TO_PERSON;
85         if (type == CONTACT_QUERY)
86                 qtype = query_type_e::QUERY_TO_CONTACT;
87
88         m_contact_query_service = query_init(&error, qtype);
89         if (error != QUERY_SUCCESS)
90                 m_contact_query_service = NULL;
91 }
92
93 ContactSearchEngine::~ContactSearchEngine()
94 {
95         if (m_contact_query_service)
96                 query_finalize(m_contact_query_service);
97 }
98
99 void ContactSearchEngine::setCondition(FilterPtr filter)
100 {
101         if(!filter)
102                 return;
103
104         IFilterVisitorPtr filterQuery = DPL::StaticPointerCast<IFilterVisitor>(SharedFromThis());
105         filter->travel(filterQuery);
106 }
107
108 void ContactSearchEngine::setCondition(string contactId)
109 {
110         if(contactId == "")
111                 ThrowMsg(InvalidArgumentException, "contactId id empty.");
112
113         query_set_condition(m_contact_query_service, getPlatformAttr("id"), EQUAL, contactId.c_str());
114 }
115
116 void ContactSearchEngine::setSortMode(SortModePtr attr)
117 {
118         if(attr)
119         {
120                 order_e ord;
121                 if (attr->getOrder() == ASCENDING_SORT_ORDER)
122                         ord = ASC;
123                 else
124                         ord = DESC;
125
126                 query_set_order_by(m_contact_query_service, getPlatformAttr(attr->getAttributeName()), ord);
127         }
128         else
129         {
130                 query_set_order_by(m_contact_query_service, contact_attribute_e::CONTACT_ID, ASC);
131         }
132 }
133
134 void ContactSearchEngine::setAttributeOfInterest(StringArrayPtr attr)
135 {
136         if(attr)
137         {
138                 m_attributesOfInterest = attr;
139                 for (StringArray::iterator it = attr->begin(); it!=attr->end(); ++it)
140                 {
141                         query_set_attribute(m_contact_query_service, getPlatformAttr(*it));
142                 }
143         }
144         else
145         {
146                 m_attributesOfInterest = StringArrayPtr(new StringArray());
147                 for (map<string, int>::iterator it=attrEnumMap.begin(); it!=attrEnumMap.end(); it++)
148                 {
149                         if(query_set_attribute(m_contact_query_service, static_cast<contact_attribute_e>(it->second)) == QUERY_SUCCESS)
150                                 m_attributesOfInterest->push_back(it->first);
151                 }
152         }
153 }
154
155 ContactArrayPtr ContactSearchEngine::getContactSearchResult()
156 {
157         ContactArrayPtr result = ContactArrayPtr(new ContactArray());
158
159         query_error err;
160
161         contact_attribute_e pattr;
162
163         bool nameAlreadyChecked = false;
164         bool numberAlreadyChecked = false;
165         bool emailAlreadyChecked = false;
166         bool urlAlreadyChecked = false;
167         bool addrAlreadyChecked = false;
168         bool eventAlreadyChecked = false;
169         bool organizationAlreadyChecked = false;
170         bool nicknameAlreadyChecked = false;
171         bool categoryAlreadyChecked = false;
172
173         LogDebug("Start generating result set");
174
175         while ( query_get_result_contact(m_contact_query_service) == QUERY_SUCCESS )
176         {
177                 ContactPtr contact = ContactPtr(new Contact());
178
179                 for (StringArray::iterator it = m_attributesOfInterest->begin(); it != m_attributesOfInterest->end(); it++)
180                 {
181                         pattr = getPlatformAttr(*it);
182
183                         err = QUERY_SUCCESS;
184
185                         if (!nameAlreadyChecked &&
186                                         (pattr == CONTACT_ID || pattr == NAME_FIRST || pattr == NAME_LAST ||
187                                                         pattr == NAME_MIDDLE || pattr == NAME_DISPLAY))
188                         {
189                                 char* str;
190
191                                 str = query_get_attribute(m_contact_query_service, CONTACT_ID, &err);
192                                 if( str )
193                                         contact->setId(str);
194
195                                 str = query_get_attribute(m_contact_query_service, ACCOUNT_ID, &err);
196                                 if( str )
197                                         contact->getAccount()->setAccountServiceId(str);
198
199                                 str = query_get_attribute(m_contact_query_service, CONTACT_IS_FAVORITE, &err);
200                                 if( str )
201                                         contact->setIsFavorite(toBool(str));
202
203                                 str = query_get_attribute(m_contact_query_service, CONTACT_RINGTONE, &err);
204                                 if( str )
205                                         contact->setRingtoneURI(std::string("file://") + str);
206
207                                 str = query_get_attribute(m_contact_query_service, CONTACT_NOTE, &err);
208                                 if( str )
209                                 {
210                                         StringArrayPtr notes(new StringArray());
211                                         notes->push_back(str);
212                                         contact->setNotes(notes);
213                                 }
214
215                                 str = query_get_attribute(m_contact_query_service, CONTACT_PHOTO_URI, &err);
216                                 if( str )
217                                         contact->setPhotoURI(std::string("file://") + str);
218
219                                 str = query_get_attribute(m_contact_query_service, CONTACT_LAST_UPDATED_TIME_STAMP, &err);
220                                 if( str )
221                                 {
222                                         tm time_stamp;
223                                         time_t db_time_stamp = (time_t)atoi(str);
224
225                                         struct tm* tmp_time = gmtime(&db_time_stamp);
226                                         memcpy(&time_stamp, tmp_time, sizeof(tm));
227                                         contact->setLastUpdated(time_stamp);
228                                 }
229
230                                 char *firstName = query_get_attribute(m_contact_query_service, NAME_FIRST, &err);
231                                 char *lastName = query_get_attribute(m_contact_query_service, NAME_LAST, &err);
232                                 char *middleName = query_get_attribute(m_contact_query_service, NAME_MIDDLE, &err);
233                                 char *displayName = query_get_attribute(m_contact_query_service, NAME_DISPLAY, &err);
234                                 char *prefix = query_get_attribute(m_contact_query_service, NAME_PREFIX, &err);
235                                 char *phoneticName = query_get_attribute(m_contact_query_service, NAME_PHONETIC, &err);
236
237                                 setName(contact, prefix, firstName, middleName, lastName, phoneticName, displayName);
238
239                                 nameAlreadyChecked = true;
240                         }
241                         else if (!numberAlreadyChecked && (pattr == NUMBER_ADDRESS || pattr == NUMBER_TYPES))
242                         {
243                                 do
244                                 {
245                                         char *number = query_get_attribute(m_contact_query_service, NUMBER_ADDRESS, &err);
246                                         char *numType = query_get_attribute(m_contact_query_service, NUMBER_TYPES, &err);
247
248                                         setPhoneNumber(contact, number, numType);
249
250                                 } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS );
251
252                                 numberAlreadyChecked = true;
253                         }
254                         else if (!emailAlreadyChecked && (pattr == EMAIL_ADDRESS || pattr == EMAIL_TYPE))
255                         {
256                                 do
257                                 {
258                                         char *email = query_get_attribute(m_contact_query_service, EMAIL_ADDRESS, &err);
259                                         char *emailType = query_get_attribute(m_contact_query_service, EMAIL_TYPE, &err);
260
261                                         setEmailAddresses(contact, email, emailType);
262
263                                 } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS );
264
265                                 emailAlreadyChecked = true;
266                         }
267                         else if (!urlAlreadyChecked && (pattr == URL_ADDRESS || pattr == URL_TYPE))
268                         {
269                                 do
270                                 {
271                                         char *url = query_get_attribute(m_contact_query_service, URL_ADDRESS, &err);
272                                         char *urlType = query_get_attribute(m_contact_query_service, URL_TYPE, &err);
273
274                                         setUrlAddresses(contact, url, urlType);
275
276                                 } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS );
277
278                                 urlAlreadyChecked = true;
279                         }
280                         else if (!addrAlreadyChecked &&
281                                         (pattr == ADDRESS_COUNTRY || pattr == ADDRESS_REGION ||
282                                                         pattr == ADDRESS_CITY || pattr == ADDRESS_STREET ||
283                                                         pattr == ADDRESS_POSTAL_CODE || pattr == ADDRESS_ADDITIONAL) )
284                         {
285                                 do
286                                 {
287                                         char *country = query_get_attribute(m_contact_query_service, ADDRESS_COUNTRY, &err);
288                                         char *region = query_get_attribute(m_contact_query_service, ADDRESS_REGION, &err);
289                                         char *city = query_get_attribute(m_contact_query_service, ADDRESS_CITY, &err);
290                                         char *street = query_get_attribute(m_contact_query_service, ADDRESS_STREET, &err);
291                                         char *postal_code = query_get_attribute(m_contact_query_service, ADDRESS_POSTAL_CODE, &err);
292                                         char *additional = query_get_attribute(m_contact_query_service, ADDRESS_ADDITIONAL, &err);
293
294                                         setAddresses(contact, country, region, city, NULL, street, postal_code, additional);
295
296                                 } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS );
297
298                                 addrAlreadyChecked = true;
299                         }
300                         else if (!eventAlreadyChecked && (pattr == EVENT_DATE || pattr == EVENT_TYPE))
301                         {
302                                 do
303                                 {
304                                         char *event = query_get_attribute(m_contact_query_service, EVENT_DATE, &err);
305                                         char *eventType = query_get_attribute(m_contact_query_service, EVENT_TYPE, &err);
306
307                                         setEvent(contact, event, eventType);
308
309                                 } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS );
310
311                                 eventAlreadyChecked = true;
312                         }
313                         else if (!organizationAlreadyChecked &&
314                                         (pattr == ORGANIZATION_NAME || pattr == ORGANIZATION_DEPARTMENT ||
315                                                         pattr == ORGANIZATION_TITLE || pattr == ORGANIZATION_ROLE ) )
316                         {
317                                 do
318                                 {
319                                         char *orgname = query_get_attribute(m_contact_query_service, ORGANIZATION_NAME, &err);
320                                         char *org_dept = query_get_attribute(m_contact_query_service, ORGANIZATION_DEPARTMENT, &err);
321                                         char *org_title = query_get_attribute(m_contact_query_service, ORGANIZATION_TITLE, &err);
322                                         char *org_role = query_get_attribute(m_contact_query_service, ORGANIZATION_ROLE, &err);
323
324                                         setOrganization(contact, orgname, org_dept, org_title, org_role);
325
326                                 } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS );
327
328                                 organizationAlreadyChecked = true;
329                         }
330                         else if (!nicknameAlreadyChecked && (pattr == NICKNAME_NAME))
331                         {
332                                 ContactNamePtr contactName(NULL);
333
334                                 if(!contact->getNameIsSet())
335                                         contactName = ContactNamePtr(new ContactName());
336                                 else
337                                         contactName = contact->getName();
338
339                                 do
340                                 {
341                                         char *nickname = query_get_attribute(m_contact_query_service, NICKNAME_NAME, &err);
342                                         if(nickname)
343                                                 contactName->addNickname(string(nickname));
344
345                                 } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS );
346
347                                 if(!contact->getNameIsSet())
348                                         contact->setName(contactName);
349
350                                 nicknameAlreadyChecked = true;
351                         }
352                         else if (!categoryAlreadyChecked && (pattr == CATEGORY_INFO))
353                         {
354                                 do
355                                 {
356                                         char *category = query_get_attribute(m_contact_query_service, CATEGORY_INFO, &err);
357                                         if(category)
358                                                 contact->addCategory(string(category));
359
360                                 } while ( fetch_next_row(m_contact_query_service) == QUERY_SUCCESS );
361
362                                 categoryAlreadyChecked = true;
363                         }
364
365                 }
366                 nameAlreadyChecked = false;
367                 numberAlreadyChecked = false;
368                 emailAlreadyChecked = false;
369                 urlAlreadyChecked = false;
370                 addrAlreadyChecked = false;
371                 eventAlreadyChecked = false;
372                 organizationAlreadyChecked = false;
373                 nicknameAlreadyChecked = false;
374                 categoryAlreadyChecked = false;
375
376                 result->push_back(contact);
377         }
378
379         LogDebug("entered, end generating result set");
380         return result;
381 }
382
383 void ContactSearchEngine::visitPreComposite(FilterType& type, int depth)
384 {
385         query_set_condition_append(m_contact_query_service, LEFT_BRACKET);
386 }
387
388 void ContactSearchEngine::visitInComposite(FilterType& type, int depth)
389 {
390         if(type == UNION_FILTER)
391                 query_set_condition_append(m_contact_query_service, OR);
392         else if(type == INTERSECTION_FILTER)
393                 query_set_condition_append(m_contact_query_service, AND);
394 }
395
396 void ContactSearchEngine::visitPostComposite(FilterType& type, int depth)
397 {
398         query_set_condition_append(m_contact_query_service, RIGHT_BRACKET);
399 }
400
401 void ContactSearchEngine::visitAttribute(string& attrName, MatchFlag& matchFlag, AnyPtr& matchValue, int depth)
402 {
403         if(matchValue == NULL)
404                 return;
405
406         contact_attribute_e attr;
407         attr = getPlatformAttr(attrName);
408
409         string matchValueStr;
410
411         if(matchFlag == MATCH_EXISTS)
412         {
413                 query_set_condition(m_contact_query_service, attr, EXISTS, NULL);
414         }
415         else
416         {
417                 condition_e cond;
418                 if(matchFlag == MATCH_EXACTLY)
419                         cond = EQUAL;
420                 else if (matchFlag == MATCH_STARTSWITH || matchFlag == MATCH_ENDSWITH)
421                         cond = LIKE;
422                 else
423                         cond = EQUAL;
424
425                 visitAttributeEach(attr, matchValue, cond);
426         }
427 }
428
429 void ContactSearchEngine::visitAttributeRange(string& attrName, AnyPtr& initialValue, AnyPtr& endValue, int depth)
430 {
431         if(initialValue == NULL || endValue == NULL)
432                 return;
433
434         contact_attribute_e attr;
435         string initialValueStr;
436         string endValueStr;
437
438         if(initialValue->isType(PrimitiveType_Time))
439         {
440                 tm date = initialValue->getDateTm();
441                 initialValueStr = toDateDbStr(date);
442         }
443         else
444         {
445                 initialValueStr = initialValue->toString();
446         }
447
448         if(endValue->isType(PrimitiveType_Time))
449         {
450                 tm date = endValue->getDateTm();
451                 endValueStr = toDateDbStr(date);
452         }
453         else
454         {
455                 endValueStr = endValue->toString();
456         }
457
458         attr = getPlatformAttr(attrName);
459         query_set_condition_append(m_contact_query_service, LEFT_BRACKET);
460         query_set_condition(m_contact_query_service, attr, GREATER_THAN_OR_EQUAL, ("\"" + initialValueStr + "\"").c_str());
461         query_set_condition_append(m_contact_query_service, AND);
462         query_set_condition(m_contact_query_service, attr, LESS_THAN_OR_EQUAL, ("\"" + endValueStr + "\"").c_str());
463         query_set_condition_append(m_contact_query_service, RIGHT_BRACKET);
464 }
465
466 void ContactSearchEngine::visitAttributeEach(contact_attribute_e attr, AnyPtr& matchValue, condition_e flag)
467 {
468         string valueStr;
469         if(matchValue->isType(PrimitiveType_Time))
470         {
471                 tm date = matchValue->getDateTm();
472                 valueStr = toDateDbStr(date);
473         }
474         else
475         {
476                 valueStr = matchValue->toString();
477         }
478
479         query_set_condition(m_contact_query_service, attr, flag, valueStr.c_str());
480 }
481
482 void ContactSearchEngine::visitAttributeID(AnyArrayPtr &ids)
483 {
484         if (ids->size() == 1)
485         {
486                 query_set_condition(m_contact_query_service, getPlatformAttr("id"), EQUAL, ids->at(0)->toString().c_str());
487         }
488         else if (ids->size() > 1)
489         {
490                 query_set_condition_with_indices_begin(m_contact_query_service);
491
492                 for (AnyArray::iterator iter = ids->begin(); iter != ids->end(); iter++)
493                         query_set_condition_with_indices(m_contact_query_service, (*iter)->toString().c_str());
494
495                 query_set_condition_with_indices_end(m_contact_query_service);
496         }
497 }
498
499 contact_attribute_e ContactSearchEngine::getPlatformAttr(string attrName)
500 {
501         contact_attribute_e platformAttr = contact_attribute_e::ATTRIBUTE_MAX;
502
503         platformAttr = (contact_attribute_e) attrEnumMap.find(attrName)->second;
504         if (platformAttr >= ATTRIBUTE_MAX)
505         {
506                 ThrowMsg(UnsupportedException, "Attribute(" << attrName << ") is not supported.");
507         }
508
509         return platformAttr;
510 }
511
512 #if 0
513 void ContactSearchEngine::setPlatformAttrValue(Contact& contact, contact_attribute_e attr, char* val)
514 {
515         if(!val)
516                 return;
517
518         switch (attr)
519         {
520         case CONTACT_ID:
521                 contact.setId(string(val));
522                 break;
523         case CONTACT_IS_FAVORITE:
524                 contact.setIsFavorite(toBool(val));
525                 break;
526         case CONTACT_RINGTONE:
527                 contact.setRingtoneURI(string(val));
528                 break;
529         case CONTACT_NOTE:
530                 contact.addNote(string(val));
531                 break;
532         case CONTACT_PHOTO_URI:
533                 contact.setPhotoURI(string(val));
534                 break;
535 //      CONTACT_READ_ONLY,
536 //      CONTACT_SEND_TO_VOICE_MAIL,
537         case CONTACT_LAST_UPDATED_TIME_STAMP:
538                 contact.setLastUpdated(toDateTm(val));
539                 break;
540
541 //      CONTACT_LATITUDE,
542 //      CONTACT_LONGITUDE,
543         case NAME_FIRST:
544                 contact.setFirstName(string(val));
545                 break;
546         case NAME_MIDDLE:
547                 contact.setMiddleName(string(val));
548                 break;
549         case NAME_LAST:
550                 contact.setLastName(string(val));
551                 break;
552         case NAME_PREFIX:
553                 contact.setPrefix(string(val));
554                 break;
555         case NAME_PHONETIC:
556                 contact.setPhoneticName(string(val));
557                 break;
558         case NAME_DISPLAY:
559                 contact.setDisplayName(string(val));
560                 break;
561         case NICKNAME_NAME:
562                 contact.addNickname(string(val));
563                 break;
564         case NUMBER_ADDRESS:
565         case NUMBER_TYPES:
566                 break;
567         case EMAIL_ADDRESS:
568         case EMAIL_TYPE:
569                 break;
570
571         case URL_ADDRESS:
572         case URL_TYPE:
573                 break;
574
575         case ADDRESS_COUNTRY:
576         case ADDRESS_REGION:
577 //      case ADDRESS_COUNTY:
578         case ADDRESS_CITY:
579         case ADDRESS_STREET:
580         case ADDRESS_POSTAL_CODE:
581         case ADDRESS_ADDITIONAL:
582                 break;
583
584         case CATEGORY_INFO:
585                 contact.addCategory(string(val));
586                 break;
587         case EVENT_DATE:
588         case EVENT_TYPE:
589                 break;
590
591 //      ORGANIZATION_NAME = 140,
592 //      ORGANIZATION_DEPARTMENT,
593 ////    ORGANIZATION_OFFICE,
594 //      ORGANIZATION_TITLE,
595 //      ORGANIZATION_ROLE,
596 ////    ORGANIZATION_LOGO_URI,
597
598 // NOT COMPLETE YET
599 //      PRESENCE_STATE = 160,
600 //      PRESENCE_MESSAGE,
601 //      PRESENCE_ICON_URI,
602 //      PRESENCE_CAPABILITY,
603 //      PRESENCE_IM_ADDR,
604 //
605 //      ATTRIBUTE_MAX = 1000
606         default:
607                 break;
608         }
609 }
610 #endif
611
612 void ContactSearchEngine::setName(ContactPtr& contact,
613                 char *prefix, char *firstName, char *middleName,
614                 char *lastName, char *phoneticName, char *displayName)
615 {
616         if(prefix == NULL && firstName == NULL && middleName == NULL
617                         && lastName == NULL && phoneticName == NULL && displayName == NULL)
618                 return;
619
620         ContactNamePtr contactName(NULL);
621
622         if(!contact->getNameIsSet())
623                 contactName = ContactNamePtr(new ContactName);
624         else
625                 contactName = contact->getName();
626
627         if( prefix )
628                 contactName->setFirstName(prefix);
629
630         if( firstName )
631                 contactName->setLastName(firstName);
632
633         if( middleName )
634                 contactName->setMiddleName(middleName);
635
636         if( lastName )
637                 contactName->setDisplayName(lastName);
638
639         if( phoneticName )
640                 contactName->setPrefix(phoneticName);
641
642         if( phoneticName )
643                 contactName->setPhoneticName(phoneticName);
644
645         if(!contact->getNameIsSet())
646                 contact->setName(contactName);
647 }
648
649 void ContactSearchEngine::setPhoneNumber(ContactPtr& contact, char *number, char *type)
650 {
651         if(number == NULL)
652                 return;
653
654         ContactPhoneNumberPtr numberType = ContactPhoneNumberPtr(new ContactPhoneNumber());
655
656         if(number)
657                 numberType->setNumber(string(number));
658
659         if(type)
660         {
661                 vector<string> tokens;
662                 tokenize(type,tokens, ",");
663
664                 for (unsigned int i=0; i<tokens.size(); i++)
665                 {
666                         if (tokens[i].compare("WORK") == 0)
667                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_WORK);
668                         else if (tokens[i].compare("PREF"))
669                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_PREF);
670                         else if (tokens[i].compare("HOME"))
671                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_HOME);
672                         else if (tokens[i].compare("VOICE"))
673                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_VOICE);
674                         else if (tokens[i].compare("FAX"))
675                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_FAX);
676                         else if (tokens[i].compare("MSG"))
677                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_MSG);
678                         else if (tokens[i].compare("CELL"))
679                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_CELL);
680                         else if (tokens[i].compare("PAGER"))
681                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_PAGER);
682                         else if (tokens[i].compare("BBS"))
683                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_BBS);
684                         else if (tokens[i].compare("MODEM"))
685                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_MODEM);
686                         else if (tokens[i].compare("CAR"))
687                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_CAR);
688                         else if (tokens[i].compare("IDSN"))
689                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_ISDN);
690                         else if (tokens[i].compare("VIDEO"))
691                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_VIDEO);
692                         else if (tokens[i].compare("PCS"))
693                                 numberType->addType(CONTACT_PHONE_NUMBER_TYPE_PCS);
694                 }
695         }
696
697         contact->addPhoneNumber(numberType);
698 }
699
700 void ContactSearchEngine::setEmailAddresses(ContactPtr& contact, char *email, char *type)
701 {
702         if(email == NULL)
703                 return;
704
705         ContactEmailAddressPtr emailAddr = ContactEmailAddressPtr(new ContactEmailAddress());
706
707         if(email)
708                 emailAddr->setEmail(string(email));
709
710         if(type)
711         {
712                 vector<string> tokens;
713                 tokenize(type,tokens, ",");
714                 for (unsigned int i=0; i<tokens.size(); i++)
715                 {
716                         if (tokens[i].compare("WORK") == 0)
717                                 emailAddr->addType(CONTACT_EMAIL_TYPE_WORK);
718                         else if (tokens[i].compare("PREF"))
719                                 emailAddr->addType(CONTACT_EMAIL_TYPE_PREF);
720                         else if (tokens[i].compare("HOME"))
721                                 emailAddr->addType(CONTACT_EMAIL_TYPE_HOME);
722                 }
723         }
724
725         contact->addEmail(emailAddr);
726 }
727
728 void ContactSearchEngine::setUrlAddresses(ContactPtr& contact, char *url, char *type)
729 {
730         if(url == NULL)
731                 return;
732
733         ContactWebSitePtr urlType = ContactWebSitePtr(new ContactWebSite());
734
735         if(url)
736                 urlType->setUrl(string(url));
737
738         if(type)
739         {
740                 vector<string> tokens;
741                 tokenize(type,tokens, ",");
742                 for (unsigned int i=0; i<tokens.size(); i++)
743                 {
744                         if (tokens[i].compare("HOMEPAGE") == 0)
745                                 urlType->setType(WEBSITE_TYPE_HOMEPAGE);
746                         else if (tokens[i].compare("BLOG") == 0)
747                                 urlType->setType(WEBSITE_TYPE_BLOG);
748                 }
749         }
750
751         contact->addUrl(urlType);
752 }
753
754 void ContactSearchEngine::setAddresses(ContactPtr& contact,
755                 char *country, char *region, char* city, char *county, char *street, char *postal_code, char *additional)
756 {
757         if(country == NULL && region == NULL && city == NULL && county == NULL &&
758                         street == NULL && postal_code == NULL && additional == NULL)
759                 return;
760
761         ContactAddressPtr addr = ContactAddressPtr(new ContactAddress());
762
763         if(country)
764                 addr->setCountry(string(country));
765
766         if(region)
767                 addr->setRegion(string(region));
768
769         if(city)
770                 addr->setCity(string(city));
771
772         if(street)
773                 addr->setStreetAddress(string(street));
774
775         if(postal_code)
776                 addr->setPostalCode(string(postal_code));
777
778         if(additional)
779                 addr->setAdditionalInformation(string(additional));
780
781         contact->addAddress(addr);
782 }
783
784 void ContactSearchEngine::setEvent(ContactPtr& contact, char *date, char *type)
785 {
786         if(date == NULL)
787                 return;
788
789         tm tm_date = toDateTmFromDateDbStr(date);
790
791         if(type != NULL)
792         {
793                 if(strcmp(type, "BIRTHDAY") == 0)
794                 {
795                         contact->setBirthday(tm_date);
796                 }
797                 else if(strcmp(type, "ANNIVERSARY") == 0)
798                 {
799                         ContactAnniversaryPtr anniv = ContactAnniversaryPtr(new ContactAnniversary());
800
801                         anniv->setDate(tm_date);
802                         //if(type)
803                         //      anniv->setLabel(string(type));
804
805                         contact->addAnniversary(anniv);
806                 }
807         }
808         else
809                 LogDebug("type is null");
810 }
811
812 void ContactSearchEngine::setOrganization(ContactPtr& contact,
813                 char* org_name, char* org_dept, char* org_title, char* org_role)
814 {
815         if(org_name == NULL && org_dept == NULL && org_title == NULL && org_role == NULL)
816                 return;
817
818         ContactOrganizationPtr org = ContactOrganizationPtr(new ContactOrganization());
819
820         if(org_name)
821                 org->setName(string(org_name));
822
823         if(org_dept)
824                 org->setDepartment(string(org_dept));
825
826         if(org_title)
827                 org->setTitle(string(org_title));
828
829         if(org_role)
830                 org->setRole(string(org_role));
831
832         contact->setOrganization(org);
833 }
834
835 void ContactSearchEngine::tokenize(const string& str, vector<string>& tokens, const string& delimiters)
836 {
837         // Skip delimiters at beginning.
838         string::size_type lastPos = str.find_first_not_of(delimiters, 0);
839         // Find first "non-delimiter".
840         string::size_type pos = str.find_first_of(delimiters, lastPos);
841
842         while (string::npos != pos || string::npos != lastPos)
843         {
844                 // Found a token, add it to the vector.
845                 tokens.push_back(str.substr(lastPos, pos - lastPos));
846                 // Skip delimiters.  Note the "not_of"
847                 lastPos = str.find_first_not_of(delimiters, pos);
848                 // Find next "non-delimiter"
849                 pos = str.find_first_of(delimiters, lastPos);
850         }
851 }
852
853 bool ContactSearchEngine::toBool(char* val)
854 {
855         string boolStr(val);
856
857         if (boolStr == "true" || boolStr == "TRUE")
858                 return true;
859
860         return false;
861 }
862
863 tm ContactSearchEngine::toDateTm(char* arg)
864 {
865         // this code originated from Converter
866         struct tm result;
867         char* currentLocale = setlocale(LC_TIME, NULL);
868         if (currentLocale == NULL) {
869                 ThrowMsg(ConversionException, "Couldn't get current locale.");
870         }
871         DPL::ScopedFree<char> currentLocaleCopy(strdup(currentLocale));
872         if (setlocale(LC_TIME, "C") == NULL) {
873                 ThrowMsg(ConversionException, "Couldn't set POSIX locale.");
874         }
875         if (strptime(arg, "%a %b %d %Y %T", &result) == NULL) {
876                 ThrowMsg(ConversionException, "Couldn't convert supplied date.");
877         }
878         if (setlocale(LC_TIME, currentLocaleCopy.Get()) == NULL) {
879                 ThrowMsg(ConversionException, "Couldn't set previous locale back.");
880         }
881         return result;
882 }
883
884 string ContactSearchEngine::toDateDbStr(const tm &date) const
885 {
886         stringstream ss;
887         ss << setfill('0') << setiosflags(ios::right) << setw(4) << (date.tm_year + 1900);
888         ss << setfill('0') << setiosflags(ios::right) << setw(2) << (date.tm_mon + 1);
889         ss << setfill('0') << setiosflags(ios::right) << setw(2) << date.tm_mday;
890
891         return ss.str();
892 }
893
894 tm ContactSearchEngine::toDateTmFromDateDbStr(const char* arg) const
895 {
896         tm date;
897
898         if(arg == NULL) {
899                 ThrowMsg(InvalidArgumentException, "Invalid Date type");
900         }
901
902         int dateDb;
903         stringstream ss(arg);
904         ss >> dateDb;
905
906         date.tm_year = (dateDb / 10000) - 1900;
907         date.tm_mon = ((dateDb - ((date.tm_year + 1900) * 10000)) / 100) - 1;
908         date.tm_mday = (dateDb - ((date.tm_year + 1900) * 10000) - date.tm_mon * 100);
909
910         return date;
911 }
912
913 } // Contact
914 } // Platform
915 } // TizenApis