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/sync/glue/search_engine_data_type_controller.h"
6
7#include "base/metrics/histogram.h"
8#include "chrome/browser/profiles/profile.h"
9#include "chrome/browser/search_engines/template_url_service_factory.h"
10#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
11#include "chrome/browser/sync/profile_sync_service.h"
12#include "content/public/browser/browser_thread.h"
13#include "sync/api/syncable_service.h"
14
15using content::BrowserThread;
16
17namespace browser_sync {
18
19SearchEngineDataTypeController::SearchEngineDataTypeController(
20    sync_driver::SyncApiComponentFactory* sync_factory,
21    Profile* profile)
22    : UIDataTypeController(
23          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI),
24          base::Bind(&ChromeReportUnrecoverableError),
25          syncer::SEARCH_ENGINES,
26          sync_factory),
27      profile_(profile) {
28}
29
30TemplateURLService::Subscription*
31SearchEngineDataTypeController::GetSubscriptionForTesting() {
32  return template_url_subscription_.get();
33}
34
35SearchEngineDataTypeController::~SearchEngineDataTypeController() {}
36
37// We want to start the TemplateURLService before we begin associating.
38bool SearchEngineDataTypeController::StartModels() {
39  // If the TemplateURLService is loaded, continue with association. We force
40  // a load here to prevent the rest of Sync from waiting on
41  // TemplateURLService's lazy load.
42  TemplateURLService* turl_service =
43      TemplateURLServiceFactory::GetForProfile(profile_);
44  DCHECK(turl_service);
45  turl_service->Load();
46  if (turl_service->loaded()) {
47    return true;  // Continue to Associate().
48  }
49
50  // Register a callback and continue when the TemplateURLService is loaded.
51  template_url_subscription_ = turl_service->RegisterOnLoadedCallback(
52      base::Bind(&SearchEngineDataTypeController::OnTemplateURLServiceLoaded,
53                 this));
54
55  return false;  // Don't continue Start.
56}
57
58void SearchEngineDataTypeController::StopModels() {
59  template_url_subscription_.reset();
60}
61
62void SearchEngineDataTypeController::OnTemplateURLServiceLoaded() {
63  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
64  DCHECK_EQ(state_, MODEL_STARTING);
65  template_url_subscription_.reset();
66  OnModelLoaded();
67}
68
69}  // namespace browser_sync
70