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 "components/policy/core/common/cloud/cloud_policy_core.h"
6
7#include "base/bind.h"
8#include "base/bind_helpers.h"
9#include "base/prefs/pref_service.h"
10#include "components/policy/core/common/cloud/cloud_policy_client.h"
11#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h"
12#include "components/policy/core/common/cloud/cloud_policy_service.h"
13#include "components/policy/core/common/cloud/cloud_policy_store.h"
14
15namespace policy {
16
17CloudPolicyCore::Observer::~Observer() {}
18
19CloudPolicyCore::CloudPolicyCore(
20    const PolicyNamespaceKey& key,
21    CloudPolicyStore* store,
22    const scoped_refptr<base::SequencedTaskRunner>& task_runner)
23    : policy_ns_key_(key),
24      store_(store),
25      task_runner_(task_runner) {}
26
27CloudPolicyCore::~CloudPolicyCore() {}
28
29void CloudPolicyCore::Connect(scoped_ptr<CloudPolicyClient> client) {
30  CHECK(!client_);
31  CHECK(client);
32  client_ = client.Pass();
33  service_.reset(new CloudPolicyService(policy_ns_key_, client_.get(), store_));
34  FOR_EACH_OBSERVER(Observer, observers_, OnCoreConnected(this));
35}
36
37void CloudPolicyCore::Disconnect() {
38  if (client_)
39    FOR_EACH_OBSERVER(Observer, observers_, OnCoreDisconnecting(this));
40  refresh_delay_.reset();
41  refresh_scheduler_.reset();
42  service_.reset();
43  client_.reset();
44}
45
46void CloudPolicyCore::RefreshSoon() {
47  if (refresh_scheduler_)
48    refresh_scheduler_->RefreshSoon();
49}
50
51void CloudPolicyCore::StartRefreshScheduler() {
52  if (!refresh_scheduler_) {
53    refresh_scheduler_.reset(
54        new CloudPolicyRefreshScheduler(client_.get(), store_, task_runner_));
55    UpdateRefreshDelayFromPref();
56    FOR_EACH_OBSERVER(Observer, observers_, OnRefreshSchedulerStarted(this));
57  }
58}
59
60void CloudPolicyCore::TrackRefreshDelayPref(
61    PrefService* pref_service,
62    const std::string& refresh_pref_name) {
63  refresh_delay_.reset(new IntegerPrefMember());
64  refresh_delay_->Init(
65      refresh_pref_name.c_str(), pref_service,
66      base::Bind(&CloudPolicyCore::UpdateRefreshDelayFromPref,
67                 base::Unretained(this)));
68  UpdateRefreshDelayFromPref();
69}
70
71void CloudPolicyCore::AddObserver(CloudPolicyCore::Observer* observer) {
72  observers_.AddObserver(observer);
73}
74
75void CloudPolicyCore::RemoveObserver(CloudPolicyCore::Observer* observer) {
76  observers_.RemoveObserver(observer);
77}
78
79void CloudPolicyCore::UpdateRefreshDelayFromPref() {
80  if (refresh_scheduler_ && refresh_delay_)
81    refresh_scheduler_->SetRefreshDelay(refresh_delay_->GetValue());
82}
83
84}  // namespace policy
85