import json
import pprint
import time
from urlparse import urlparse

import requests
from requests import HTTPError

OAUTH_TOKEN = '' # your token as string
AUTH_HEADER = {
    'Authorization': 'OAuth %s' % OAUTH_TOKEN
}

SESSION = requests.Session()
SESSION.headers.update(AUTH_HEADER)

API_VERSION = 'v4.1'
API_BASE_URL = 'http://webmaster.dev.search.yandex.net:33545/api'
API_URL = API_BASE_URL + '/' + API_VERSION


def validate_api_response(response, required_keys=None):
    if required_keys is None:
        required_keys = []
    content_type = response.headers['Content-Type']
    content = json.loads(response.text) if 'application/json' in content_type else None

    if response.status_code == 200:
        for required_key in required_keys:
            if required_key and required_key not in content:
                raise HTTPError('Unexpected API response. Missing required key: %s' % required_key, response=response)
    elif content and 'error_message' in content:
        raise HTTPError('Error API response. Error message: %s' % content['error_message'], response=response)
    else:
        response.raise_for_status()

    return content


def url_to_host_id(url):
    parsed_url = urlparse(url)

    scheme = parsed_url.scheme
    if not scheme:
        raise ValueError('No protocol (https or http) in url')

    if scheme != 'http' and scheme != 'https':
        raise ValueError('Illegal protocol: %s' % scheme)

    port = parsed_url.port
    if not port:
        port = 80 if scheme == 'http' else 443

    hostname = parsed_url.hostname
    hostname = hostname.encode('idna').rstrip('.').lower()

    return scheme + ':' + hostname + ':' + str(port)


def get_user_id():
    r = SESSION.get(API_URL + '/user/')
    c = validate_api_response(r, ['user_id'])

    return c['user_id']


def print_json(d):
    print json.dumps(d, sort_keys=True, indent=2, ensure_ascii=False).encode('utf8')
