# coding: utf-8

from __future__ import unicode_literals

import logging

from ids.registry import registry

from cab.utils import env
from cab.utils import http
from cab.utils import helpers

log = logging.getLogger(__name__)


API_URL = env.choose({
    'production': 'https://wiki-api.yandex-team.ru',
    'testing': 'https://wiki-api.test.yandex-team.ru',
})
WEB_URL = env.choose({
    'production': 'https://wiki.yandex-team.ru',
    'testing': 'https://wiki.test.yandex-team.ru',
})
RESOURCES = {
    'page_api': API_URL + '/_api/frontend{tag}',
    'page_markup': API_URL + '/_api/frontend{tag}/.raw',
    'page_access': API_URL + '/_api/frontend{tag}/.access',
    'page_web': WEB_URL + '{tag}'
}

RESOURCES_FOR_REDIRECT = {
    'page_api': API_URL + '/_api/frontend{tag}/.bemjson',
}

WIKI_TIMEOUT = 5


@helpers.timeit
def get_page_markup(auth, tag, follow_redirect=True):
    data = fetch_page_data(
        auth=auth,
        resource='page_markup',
        tag=tag,
        follow_redirect=follow_redirect,
    )
    if data:
        return data['body']


@helpers.timeit
def get_page_structure(auth, tag, follow_redirect=True):
    data = fetch_page_data(
        auth=auth,
        resource='page_api',
        tag=tag,
        follow_redirect=follow_redirect,
    )
    if data:
        return data['bemjson']


@helpers.timeit
def fetch_page_data(auth, resource, tag, follow_redirect=True):
    session = http.get_session(auth)
    if not tag.startswith('/'):
        tag = '/' + tag

    def send_request(url):
        url = url.format(tag=tag)
        response = session.get(url=url, timeout=WIKI_TIMEOUT)
        if not response.ok:
            log.warning('Wiki responded with status %s on url %s', response.status_code, url)
            return
        try:
            return response.json()['data']
        except (ValueError, KeyError):
            log.warning('Wiki returned incorrect response on url %s', url)
            return

    data = send_request(RESOURCES[resource])
    if not data:
        return
    if 'redirect_to_tag' in data:
        if follow_redirect:
            return fetch_page_data(
                auth=auth,
                resource=resource,
                tag=data['redirect_to_tag'],
                follow_redirect=follow_redirect,
            )
    elif resource in RESOURCES_FOR_REDIRECT:
        data = send_request(RESOURCES_FOR_REDIRECT[resource])

    return data


@helpers.timeit
def markup_to_html(wiki_text):
    wf = registry.get_repository(
        service='formatter',
        resource_type='formatter',
        user_agent='staff-cab',
    )
    return wf.convert_to_html(wiki_text=wiki_text, version=3)


@helpers.timeit
def update_page(auth, tag, title, body):
    session = http.get_session(auth)
    url = RESOURCES['page_api'].format(tag=tag)

    response = session.post(
        url=url,
        json={
            'title': title,
            'body': body,
        },
        timeout=WIKI_TIMEOUT,
    )
    # TODO: возвращать response — коряво, нужно рефакторить
    return response


@helpers.timeit
def set_page_access(auth, tag, **access_data):
    """
    https://wiki.yandex-team.ru/wiki/dev/api/autodocs/#izmenitpravadostupakstranice.post-
    """
    session = http.get_session(auth)
    url = RESOURCES['page_access'].format(tag=tag)

    response = session.post(
        url=url,
        json=access_data,
        timeout=WIKI_TIMEOUT,
    )
    return response
