#!/usr/bin/env python

# Copyright (C) 2009 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.


import sys
import unittest
import getpass
import inspect
import atom.mock_http_core
import gdata.gauth


"""Loads configuration for tests which connect to Google servers.

Settings used in tests are stored in a ConfigCollection instance in this
module called options. If your test needs to get a test related setting,
use

import gdata.test_config
option_value = gdata.test_config.options.get_value('x')

The above will check the command line for an '--x' argument, and if not
found will either use the default value for 'x' or prompt the user to enter
one. 

Your test can override the value specified by the user by performing:

gdata.test_config.options.set_value('x', 'y')

If your test uses a new option which you would like to allow the user to
specify on the command line or via a prompt, you can use the register_option
method as follows:

gdata.test_config.options.register(
    'option_name', 'Prompt shown to the user', secret=False #As for password.
    'This is the description of the option, shown when help is requested.',
    'default value, provide only if you do not want the user to be prompted')
"""


class Option(object):

  def __init__(self, name, prompt, secret=False, description=None, default=None):
    self.name = name
    self.prompt = prompt
    self.secret = secret
    self.description = description
    self.default = default

  def get(self):
    value = self.default
    # Check for a command line parameter.
    for i in range(len(sys.argv)):
      if sys.argv[i].startswith('--%s=' % self.name):
        value = sys.argv[i].split('=')[1]
      elif sys.argv[i] == '--%s' % self.name:
        value = sys.argv[i + 1]
    # If the param was not on the command line, ask the user to input the
    # value.
    # In order for this to prompt the user, the default value for the option
    # must be None.
    if value is None:
      prompt = '%s: ' % self.prompt
      if self.secret:
        value = getpass.getpass(prompt)
      else:
        print('You can specify this on the command line using --%s' % self.name)
        value = input(prompt)
    return value


class ConfigCollection(object):

  def __init__(self, options=None):
    self.options = options or {}
    self.values = {}

  def register_option(self, option):
    self.options[option.name] = option

  def register(self, *args, **kwargs):
    self.register_option(Option(*args, **kwargs))

  def get_value(self, option_name):
    if option_name in self.values:
      return self.values[option_name]
    value = self.options[option_name].get()
    if value is not None:
      self.values[option_name] = value
    return value

  def set_value(self, option_name, value):
    self.values[option_name] = value

  def render_usage(self):
    message_parts = []
    for opt_name, option in self.options.items():
      message_parts.append('--%s: %s' % (opt_name, option.description))
    return '\n'.join(message_parts)


options = ConfigCollection()


# Register the default options.
options.register(
    'username',
    'Please enter the email address of your test account', 
    description=('The email address you want to sign in with. '
                 'Make sure this is a test account as these tests may edit'
                 ' or delete data.'))
options.register(
    'password',
    'Please enter the password for your test account',
    secret=True, description='The test account password.')
options.register(
    'clearcache',
    'Delete cached data? (enter true or false)',
    description=('If set to true, any temporary files which cache test'
                 ' requests and responses will be deleted.'),
    default='true')
options.register(
    'savecache',
    'Save requests and responses in a temporary file? (enter true or false)',
    description=('If set to true, requests to the server and responses will'
                 ' be saved in temporary files.'),
    default='false')
options.register(
    'runlive',
    'Run the live tests which contact the server? (enter true or false)',
    description=('If set to true, the tests will make real HTTP requests to'
                 ' the servers. This slows down test execution and may'
                 ' modify the users data, be sure to use a test account.'),
    default='true')
options.register(
    'host',
    'Run the live tests against the given host',
    description='Examples: docs.google.com, spreadsheets.google.com, etc.',
    default='')
options.register(
    'ssl',
    'Run the live tests over SSL (enter true or false)',
    description='If set to true, all tests will be performed over HTTPS (SSL)',
    default='false')
options.register(
    'clean',
    'Clean ALL data first before and after each test (enter true or false)',
    description='If set to true, all tests will remove all data (DANGEROUS)',
    default='false')
options.register(
    'appsusername',
    'Please enter the email address of your test Apps domain account', 
    description=('The email address you want to sign in with. '
                 'Make sure this is a test account on your Apps domain as '
                 'these tests may edit or delete data.'))
options.register(
    'appspassword',
    'Please enter the password for your test Apps domain account',
    secret=True, description='The test Apps account password.')

# Other options which may be used if needed.
BLOG_ID_OPTION = Option(
    'blogid',
    'Please enter the ID of your test blog',
    description=('The blog ID for the blog which should have test posts added'
                 ' to it. Example 7682659670455539811'))
TEST_IMAGE_LOCATION_OPTION = Option(
    'imgpath',
    'Please enter the full path to a test image to upload',
    description=('This test image will be uploaded to a service which'
                 ' accepts a media file, it must be a jpeg.'))
SPREADSHEET_ID_OPTION = Option(
    'spreadsheetid',
    'Please enter the ID of a spreadsheet to use in these tests',
    description=('The spreadsheet ID for the spreadsheet which should be'
                 ' modified by theses tests.'))
APPS_DOMAIN_OPTION = Option(
    'appsdomain',
    'Please enter your Google Apps domain',
    description=('The domain the Google Apps is hosted on or leave blank'
                 ' if n/a'))
SITES_NAME_OPTION = Option(
    'sitename',
    'Please enter name of your Google Site',
    description='The webspace name of the Site found in its URL.')
PROJECT_NAME_OPTION = Option(
    'project_name',
    'Please enter the name of your project hosting project',
    description=('The name of the project which should have test issues added'
                 ' to it. Example gdata-python-client'))
ISSUE_ASSIGNEE_OPTION = Option(
    'issue_assignee',
    'Enter the email address of the target owner of the updated issue.',
    description=('The email address of the user a created issue\'s owner will '
                 ' become. Example testuser2@gmail.com'))
GA_TABLE_ID = Option(
    'table_id',
    'Enter the Table ID of the Google Analytics profile to test',
    description=('The Table ID of the Google Analytics profile to test.'
                 ' Example ga:1174'))
TARGET_USERNAME_OPTION = Option(
    'targetusername',
    'Please enter the username (without domain) of the user which will be'
    ' affected by the tests',
    description=('The username of the user to be tested'))
YT_DEVELOPER_KEY_OPTION = Option(
    'developerkey',
    'Please enter your YouTube developer key',
    description=('The YouTube developer key for your account'))
YT_CLIENT_ID_OPTION = Option(
    'clientid',
    'Please enter your YouTube client ID',
    description=('The YouTube client ID for your account'))
YT_VIDEO_ID_OPTION= Option(
    'videoid',
    'Please enter the ID of a YouTube video you uploaded',
    description=('The video ID of a YouTube video uploaded to your account'))


# Functions to inject a cachable HTTP client into a service client.
def configure_client(client, case_name, service_name, use_apps_auth=False):
  """Sets up a mock client which will reuse a saved session.

  Should be called during setUp of each unit test.

  Handles authentication to allow the GDClient to make requests which
  require an auth header.

  Args:
    client: a gdata.GDClient whose http_client member should be replaced
            with a atom.mock_http_core.MockHttpClient so that repeated
            executions can used cached responses instead of contacting