1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/chromeos/contacts/contact_map.h"
6
7#include "chrome/browser/chromeos/contacts/contact.pb.h"
8
9namespace contacts {
10
11ContactMap::ContactMap() : contacts_deleter_(&contacts_) {}
12
13ContactMap::~ContactMap() {}
14
15const Contact* ContactMap::Find(const std::string& contact_id) const {
16  Map::const_iterator it = contacts_.find(contact_id);
17  return (it != contacts_.end()) ? it->second : NULL;
18}
19
20void ContactMap::Erase(const std::string& contact_id) {
21  Map::iterator it = contacts_.find(contact_id);
22  if (it == contacts_.end())
23    return;
24
25  delete it->second;
26  contacts_.erase(it);
27}
28
29void ContactMap::Clear() {
30  STLDeleteValues(&contacts_);
31}
32
33void ContactMap::Merge(scoped_ptr<ScopedVector<Contact> > updated_contacts,
34                       DeletedContactPolicy policy) {
35  for (ScopedVector<Contact>::iterator it = updated_contacts->begin();
36       it != updated_contacts->end(); ++it) {
37    Contact* contact = *it;
38    Map::iterator map_it = contacts_.find(contact->contact_id());
39
40    if (contact->deleted() && policy == DROP_DELETED_CONTACTS) {
41      // Also delete the previous version of the contact, if any.
42      if (map_it != contacts_.end()) {
43        delete map_it->second;
44        contacts_.erase(map_it);
45      }
46      delete contact;
47    } else {
48      if (map_it != contacts_.end()) {
49        delete map_it->second;
50        map_it->second = contact;
51      } else {
52        contacts_[contact->contact_id()] = contact;
53      }
54    }
55  }
56
57  // Make sure that the Contact objects that we just saved to the map won't be
58  // destroyed when |updated_contacts| is destroyed.
59  updated_contacts->weak_clear();
60}
61
62}  // namespace contacts
63