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 "chrome/browser/chromeos/timezone/timezone_provider.h"
6
7#include <algorithm>
8#include <iterator>
9
10#include "base/bind.h"
11#include "base/logging.h"
12#include "base/time/time.h"
13#include "chrome/browser/chromeos/geolocation/geoposition.h"
14#include "net/url_request/url_request_context_getter.h"
15#include "url/gurl.h"
16
17namespace chromeos {
18
19TimeZoneProvider::TimeZoneProvider(
20    net::URLRequestContextGetter* url_context_getter,
21    const GURL& url)
22    : url_context_getter_(url_context_getter), url_(url) {
23}
24
25TimeZoneProvider::~TimeZoneProvider() {
26  DCHECK(thread_checker_.CalledOnValidThread());
27}
28
29void TimeZoneProvider::RequestTimezone(
30    const Geoposition& position,
31    bool sensor,
32    base::TimeDelta timeout,
33    TimeZoneRequest::TimeZoneResponseCallback callback) {
34  TimeZoneRequest* request(new TimeZoneRequest(
35      url_context_getter_, url_, position, sensor, timeout));
36  requests_.push_back(request);
37
38  // TimeZoneProvider owns all requests. It is safe to pass unretained "this"
39  // because destruction of TimeZoneProvider cancels all requests.
40  TimeZoneRequest::TimeZoneResponseCallback callback_tmp(
41      base::Bind(&TimeZoneProvider::OnTimezoneResponse,
42                 base::Unretained(this),
43                 request,
44                 callback));
45  request->MakeRequest(callback_tmp);
46}
47
48void TimeZoneProvider::OnTimezoneResponse(
49    TimeZoneRequest* request,
50    TimeZoneRequest::TimeZoneResponseCallback callback,
51    scoped_ptr<TimeZoneResponseData> timezone,
52    bool server_error) {
53  ScopedVector<TimeZoneRequest>::iterator new_end =
54      std::remove(requests_.begin(), requests_.end(), request);
55  DCHECK_EQ(std::distance(new_end, requests_.end()), 1);
56  requests_.erase(new_end, requests_.end());
57
58  callback.Run(timezone.Pass(), server_error);
59}
60
61}  // namespace chromeos
62