import json
import logging
import requests
from django.http import HttpResponse, HttpResponseForbidden
from common.models import Job
from takeout.tvm_ticketer import Ticketer
import settings


def escape_string(s):
    return s.replace('\\', '\\\\').replace("'", "\\'").replace('"', '\\"').replace("`", "\\`")


def collect_data(uid):
    """
    Here we collect data about uid.
        select n, fd from job
        inner join social_auth_usersocialauth as sa
        on job.user_id = sa.user_id and sa.uid = yandex_uid;

n    |             fd
--------+----------------------------
170224 | 2019-03-18 16:03:08.485077
170220 | 2019-03-18 15:56:48.790528
170217 | 2019-03-18 15:52:50.188715
169714 | 2019-03-15 15:01:58.83566
169712 | 2019-03-15 14:59:26.793349
167185 | 2019-03-05 08:08:49.320442

    return: List of strings
    """

    data = []

    query = "select n, fd from job inner join social_auth_usersocialauth as sa on job.user_id = sa.user_id and sa.uid = '{}'"
    escaped_uid = escape_string(str(uid))
    jobs = Job.objects.raw(query.format(escaped_uid))
    for job in jobs:
        line = ';'.join([str(job.n), str(job.fd), 'https://overload.yandex.net/{}'.format(job.n)])
        data.append(line)
    logging.info('Takeout query for uid %s gave %d tests', uid, len(data))
    return data


def get_user_id_from_blackbox(tvm_user_ticket, blackbox_service_ticket):
    url = 'https://{host}/blackbox?method=user_ticket&userip=127.0.0.1&format=json&user_ticket={ticket}'.format(host=settings.BLACKBOX_HOST, ticket=tvm_user_ticket)
    headers = {'X-Ya-Service-Ticket': blackbox_service_ticket}
    try:
        response = requests.get(url=url, headers=headers)
        response.raise_for_status()
        users = response.json().get('users')
        if 'error' in response.json():
            logging.error('Wrong response from the blackbox. %s', response.json().get('error', ''))
            return
        if not users or not isinstance(users, list) or 'uid' not in users[0]:
            logging.error('Wrong response from the blackbox. UID is not presented.')
            return
        else:
            return users[0].get('uid').get('value', '')

    except requests.exceptions.HTTPError:
        logging.error('Wrong response from the blackbox.', exc_info=True)
    except (AttributeError, KeyError):
        logging.error('Fail parsing of the blackbox response.', exc_info=True)
    except Exception:
        logging.error('Invalid request to the blackbox.', exc_info=True)


def send_response(result='', code='', message='', tvm_ticket=''):
    if result == 'status':
        data = {'status': 'ok', 'data': [{'id': 'user_data', 'slug': 'user personal data and own\'s jobs', 'state': code}]}
        response = HttpResponse(json.dumps(data), content_type='application/json')
    elif result == 'data_deleted':
        data = {'status': 'ok'}
        response = HttpResponse(json.dumps(data), content_type='application/json')
    elif result == 'error':
        data = {'status': 'error', 'errors': [{'code': code, 'message': message}]}
        response = HttpResponse(json.dumps(data), content_type='application/json')
    else:
        data = {'status': 'error', 'errors': [{'code': 'bad_request', 'message': message}]}
        response = HttpResponseForbidden(json.dumps(data), content_type='application/json')
    response['X-Ya-Service-Ticket'] = tvm_ticket
    return response


def get_tvm_tickets():
    blackbox_service_ticket = takeout_service_ticket = error = ''
    try:
        tvm_client = Ticketer()
        blackbox_service_ticket = tvm_client.get_ticket('blackbox')
        takeout_service_ticket = tvm_client.get_ticket('takeout')
    except Exception:
        error = 'Failed to get TVM service tickets'
        logging.error(error, exc_info=True)
    return blackbox_service_ticket, takeout_service_ticket, error


def check_takeout_request(request):
    request_id = request.GET.get('request_id')
    if request_id:
        logging.info('Request %s for user status', request_id)
    else:
        error = 'No request_id in request'
        logging.error('Wrong request. %s', error)
        return 0, '', error

    user_ticket = request.META.get('HTTP_X_YA_USER_TICKET')
    if not user_ticket:
        error = 'No tvm user ticket'
        logging.error('Wrong request. %s', error)
        return 0, '', error

    service_ticket = request.META.get('HTTP_X_YA_SERVICE_TICKET')
    tvm_client = Ticketer()
    if not tvm_client.check_ticket(service_ticket):
        error = 'No valid tvm service ticket found'
        logging.error('Wrong request. %s', error)
        return 0, '', error

    return request_id, user_ticket, ''
