# Path: src/zeit/api/util.py
# def iri_to_uri(iri):
#     """Convert an Internationalized Resource Identifier to a URI."""
# 
#     parts = urlparse.urlparse(iri)
#     return urlparse.urlunparse(
#         part.encode('idna') if parti == 1 else
#             url_encode_non_ascii(part.encode('utf-8'))
#         for parti, part in enumerate(parts)
#     )
# 
# def save_xpath(element, xpath, fallback=''):
#     """Safely return the first result of an xpath expression."""
# 
#     try:
#         return element.xpath(xpath)[0]
#     except IndexError:
#         return fallback


import urllib
from flask import g, current_app
from lxml import etree
from .util import iri_to_uri, save_xpath
    score = (ranks.index(int(save_xpath(keyword, './@freq'))) + 1)
    score = int(100.0 / len(ranks) * score)
    href = 'http://www.zeit.de/schlagworte/%s/%s/index' % (types[kw_type], kw_id)
    query = 'REPLACE INTO keyword VALUES (?, ?, ?, ?, ?, ?, ?);'
    g.db.execute(query, (href, kw_id, lexical, score, kw_type, uri, value))


def __update_department(department):
    """Update the given department entity."""
    dept_id = save_xpath(department, './@label')
    if dept_id in ['startseite']:
        return
    uri = '%s/department/%s' % (current_app.config['API_URL'], dept_id)
    value = save_xpath(department, 'text()')
    href = save_xpath(department, './@href')[19:].split('/', 1)[0]
    parent = href if href != dept_id else ''
    path = parent + '/' + dept_id if parent else dept_id
    href = 'http://www.zeit.de/%s/index' % path
    query = 'REPLACE INTO department VALUES (?, ?, ?, ?, ?);'
    g.db.execute(query, (href, dept_id, parent, uri, value))


def __update_author(author):
    """Update the given author entity."""
    value = save_xpath(author, './@name')
    author_id = value.replace(' ', '-')
    uri = '%s/author/%s' % (current_app.config['API_URL'], author_id)
    initial = value.split(' ')[-1] or 'A'
    href_raw = 'http://www.zeit.de/autoren/%s/%s/index.xml'
    href = href_raw % (initial[0], value.replace(' ', '_'))

# Path: src/zeit/api/util.py
# def iri_to_uri(iri):
#     """Convert an Internationalized Resource Identifier to a URI."""
# 
#     parts = urlparse.urlparse(iri)
#     return urlparse.urlunparse(
#         part.encode('idna') if parti == 1 else
#             url_encode_non_ascii(part.encode('utf-8'))
#         for parti, part in enumerate(parts)
#     )
# 
# def save_xpath(element, xpath, fallback=''):
#     """Safely return the first result of an xpath expression."""
# 
#     try:
#         return element.xpath(xpath)[0]
#     except IndexError:
#         return fallback


# Path: src/zeit/api/metadata.py
import urllib
from flask import g, current_app
from lxml import etree
from .util import iri_to_uri, save_xpath

    score = (ranks.index(int(save_xpath(keyword, './@freq'))) + 1)
    score = int(100.0 / len(ranks) * score)
    href = 'http://www.zeit.de/schlagworte/%s/%s/index' % (types[kw_type], kw_id)
    query = 'REPLACE INTO keyword VALUES (?, ?, ?, ?, ?, ?, ?);'
    g.db.execute(query, (href, kw_id, lexical, score, kw_type, uri, value))


def __update_department(department):
    """Update the given department entity."""
    dept_id = save_xpath(department, './@label')
    if dept_id in ['startseite']:
        return
    uri = '%s/department/%s' % (current_app.config['API_URL'], dept_id)
    value = save_xpath(department, 'text()')
    href = save_xpath(department, './@href')[19:].split('/', 1)[0]
    parent = href if href != dept_id else ''
    path = parent + '/' + dept_id if parent else dept_id
    href = 'http://www.zeit.de/%s/index' % path
    query = 'REPLACE INTO department VALUES (?, ?, ?, ?, ?);'
    g.db.execute(query, (href, dept_id, parent, uri, value))


def __update_author(author):
    """Update the given author entity."""
    value = save_xpath(author, './@name')
    author_id = value.replace(' ', '-')
    uri = '%s/author/%s' % (current_app.config['API_URL'], author_id)
    initial = value.split(' ')[-1] or 'A'
    href_raw = 'http://www.zeit.de/autoren/%s/%s/index.xml'
    href = href_raw % (initial[0], value.replace(' ', '_'))

    href = href if urllib.urlopen(iri_to_uri(href)).getcode() == 200 else ''