#!/usr/bin/env python

# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Command-line application to run a query using user credentials.

You must supply a client secrets file, which would normally be bundled with
your application.
"""

import argparse


def main(project, launch_browser=True):
    # [START bigquery_auth_user_flow]
    from google_auth_oauthlib import flow

    # TODO: Use a local server in the auth flow? This is recommended but does
    #       not work if accessing the application remotely, such as over SSH or
    #       from a remote Jupyter notebook.
    # launch_browser = True

    appflow = flow.InstalledAppFlow.from_client_secrets_file(
        'client_secrets.json',
        scopes=['https://www.googleapis.com/auth/bigquery'])

    if launch_browser:
        appflow.run_local_server()
    else:
        appflow.run_console()

    credentials = appflow.credentials
    # [END bigquery_auth_user_flow]

    # [START bigquery_auth_user_query]
    from google.cloud import bigquery

    # TODO: This project will be billed for the query processing. The user must
    #       have the bigquery.jobs.create permission on this project to run a
    #       query. See:
    #       https://cloud.google.com/bigquery/docs/access-control#permissions
    # project = 'user-project-id'

    client = bigquery.Client(project=project, credentials=credentials)

    query_string = """SELECT name, SUM(number) as total
    FROM `bigquery-public-data.usa_names.usa_1910_current`
    WHERE name = 'William'
    GROUP BY name;
    """
    query_job = client.query(query_string)

    # Print the results.
    for row in query_job.result():  # Wait for the job to complete.
        print("{}: {}".format(row['name'], row['total']))
    # [END bigquery_auth_user_query]


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        '--launch-browser',
        help='Use a local server flow to authenticate. ',
        action='store_true')
    parser.add_argument('project', help='Project to use for BigQuery billing.')

    args = parser.parse_args()

    main(
        args.project, launch_browser=args.launch_browser)

@@ -911,18 +911,168 @@
  TODO: U
-se
+ncomment the line below to set the %60launch_browser%60 variable.%0A    # launch_browser = True%0A    #%0A    # The %60launch_browser%60 boolean variable indicates if
  a local
@@ -1085,16 +1085,22 @@
 r in the
+%0A    #
  auth fl
@@ -1105,14 +1105,27 @@
 flow
-? This
+. A value of %60True%60
  is 
@@ -1139,33 +1139,43 @@
 nded
+,
  but 
-does%0A    #       not
+a local server does not%0A    #
  wor
@@ -1238,27 +1238,21 @@
 H or
-%0A    #      
  from a
+%0A    #
  rem
@@ -1276,36 +1276,8 @@
 ook.
-%0A    # launch_browser = True
 %0A%0A  
@@ -1697,25 +1697,155 @@
 DO: 
-This project will
+Uncomment the line below to set the %60project%60 variable.%0A    # project = 'user-project-id'%0A    #%0A    # The %60project%60 variable defines the project to
  be 
@@ -1859,17 +1859,19 @@
 for 
-the 
 query
+%0A    #
  pro
@@ -1892,28 +1892,16 @@
 ser must
-%0A    #      
  have th
@@ -1936,16 +1936,22 @@
 ssion on
+%0A    #
  this pr
@@ -1964,28 +1964,16 @@
 to run a
-%0A    #      
  query. 
@@ -1982,22 +1982,16 @@
 e:%0A    #
-      
  https:/
@@ -2052,42 +2052,8 @@
 ions
-%0A    # project = 'user-project-id'
 %0A%0A  

Make TODO clearer what action to take. (#1963)