1// Copyright 2014 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 "third_party/libaddressinput/chromium/addressinput_util.h"
6
7#include <algorithm>
8
9#include "base/logging.h"
10#include "base/macros.h"
11#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
12#include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_metadata.h"
13
14namespace autofill {
15namespace addressinput {
16
17namespace {
18
19using ::i18n::addressinput::AddressData;
20using ::i18n::addressinput::AddressField;
21using ::i18n::addressinput::AddressProblem;
22using ::i18n::addressinput::IsFieldRequired;
23
24using ::i18n::addressinput::MISSING_REQUIRED_FIELD;
25
26// Returns true if the |problem| should not be reported for the |field| because
27// the |filter| excludes it.
28bool FilterExcludes(const std::multimap<AddressField, AddressProblem>* filter,
29                    AddressField field,
30                    AddressProblem problem) {
31  return filter != NULL && !filter->empty() &&
32         std::find(filter->begin(),
33                   filter->end(),
34                   std::multimap<AddressField, AddressProblem>::value_type(
35                       field, problem)) == filter->end();
36}
37
38}  // namespace
39
40bool HasAllRequiredFields(const AddressData& address_to_check) {
41  std::multimap<AddressField, AddressProblem> problems;
42  ValidateRequiredFields(address_to_check, NULL, &problems);
43  return problems.empty();
44}
45
46void ValidateRequiredFields(
47    const AddressData& address_to_check,
48    const std::multimap<AddressField, AddressProblem>* filter,
49    std::multimap<AddressField, AddressProblem>* problems) {
50  DCHECK(problems);
51
52  static const AddressField kFields[] = {
53      ::i18n::addressinput::COUNTRY,
54      ::i18n::addressinput::ADMIN_AREA,
55      ::i18n::addressinput::LOCALITY,
56      ::i18n::addressinput::DEPENDENT_LOCALITY,
57      ::i18n::addressinput::SORTING_CODE,
58      ::i18n::addressinput::POSTAL_CODE,
59      ::i18n::addressinput::STREET_ADDRESS,
60      // ORGANIZATION is never required.
61      ::i18n::addressinput::RECIPIENT
62  };
63
64  for (size_t i = 0; i < arraysize(kFields); ++i) {
65    AddressField field = kFields[i];
66    if (address_to_check.IsFieldEmpty(field) &&
67        IsFieldRequired(field, address_to_check.region_code) &&
68        !FilterExcludes(filter, field, MISSING_REQUIRED_FIELD)) {
69      problems->insert(std::make_pair(field, MISSING_REQUIRED_FIELD));
70    }
71  }
72}
73
74}  // namespace addressinput
75}  // namespace autofill
76