# -*- coding: utf-8 -*-
from copy import copy, deepcopy
import json

from django.core.management.base import BaseCommand
from events.arc_compat import read_asset


def special_title(value):
    """
        >> special_cap('x-geobase-id')
        X-Geobase-Id
    """
    return '-'.join([i.title() for i in value.split('-')])


class Ammo(object):
    """
    Как формировать запросы https://github.com/yandex-load/yandex-tank#request-style
    Пример формирования запроса https://gist.github.com/direvius/3884148
    """
    default_headers = {
        'host': 'localhost',
        'user-agent': 'xxx (shell 1)',
        'accept': 'text/html'
    }

    def __init__(self, requests, base_headers=None):
        self.base_headers = base_headers
        self._init_base_headers()
        self.requests = requests

    def _init_base_headers(self):
        if not self.base_headers:
            self.base_headers = {}
        for key, value in self.default_headers.items():
            self.base_headers.setdefault(key, value)

    def get_requests(self):
        response = []
        for request in self.requests:
            response.append(self._get_prepared_request(request=request))
        return response

    def _get_prepared_request(self, request):
        headers = copy(self.base_headers)
        prepared_request = deepcopy(request)
        if 'headers' in prepared_request:
            headers.update(copy(prepared_request['headers']))
        prepared_request['headers'] = headers
        return prepared_request

    def get_text(self):
        """
        73 good
        GET / HTTP/1.1
        Host: xxx.tanks.example.com
        User-Agent: xxx (shell 1)
        """
        response = []
        for item in self.get_requests():
            response.append(self._get_request_text_item(item))
        return ''.join(response)

    def _get_request_text_item(self, item):
        # request
        response = '{method} {uri} HTTP/1.1\r\n'.format(method=item['method'], uri=item['uri'])
        # headers
        response += '\r\n'.join(['%s: %s' % (special_title(key), value) for key, value in item['headers'].items()])
        response += '\r\n' * 2
        # body
        if 'body' in item:
            response += item['body']
            response += '\r\n'
        response = response.encode('utf-8')
        length = len(response)
        tag = item.get('tag')
        if tag:
            tag = ' ' + tag
        else:
            tag = ''
        return '{length}{tag}\n{response}'.format(length=length, tag=tag, response=response)


class Command(BaseCommand):
    help = """Generate ammo for stress testing"""

    def handle(self, *args, **options):
        if args:
            source = args[0]
        else:
            source = None
        if source:
            requests = json.loads(read_asset(source).read().decode('utf-8'))
        else:
            requests = self.get_api_requests()

        print(Ammo(
            base_headers={
                'host': 'api.tech.yandex.ru',
                'accept': 'application/json'
            },
            requests=requests
        ).get_text())

    def get_api_requests(self):
        return [
            # info
            {
                'method': 'GET',
                'uri': '/v1/info/',
                'tag': 'info_list',
            },
            {
                'method': 'GET',
                'uri': '/v1/info/research/',
                'tag': 'info_detail',
            },

            # surveys
            {
                'method': 'GET',
                'uri': '/v1/surveys/',
                'tag': 'survey_list',
            },
            {
                'method': 'GET',
                'uri': '/v1/surveys/1/',
                'tag': 'survey_detail',
            },
            {
                'method': 'GET',
                'uri': '/v1/surveys/1/',
                'tag': 'survey_detail',
            },
            {
                'method': 'GET',
                'uri': '/v1/surveys/1/form/',
                'tag': 'survey_form',
            },

            # cities
            {
                'method': 'GET',
                'uri': '/v1/cities/',
                'tag': 'city_list',
            },
            {
                'method': 'GET',
                'uri': '/v1/cities/1/',
                'tag': 'city_detail',
            },
            {
                'method': 'GET',
                'uri': '/v1/cities/suggest/?part=se&callback=jquery',
                'tag': 'city_suggest',
            },

            # cities
            {
                'method': 'GET',
                'uri': '/v1/countries/',
                'tag': 'country_list',
            },
            {
                'method': 'GET',
                'uri': '/v1/countries/1/',
                'tag': 'country_detail',
            },
            {
                'method': 'GET',
                'uri': '/v1/countries/suggest/?part=s&callback=jquery',
                'tag': 'country_suggest',
            },

            # users
            {
                'method': 'GET',
                'uri': '/v1/users/',
                'tag': 'user_list',
            },
            {
                'method': 'GET',
                'uri': '/v1/users/4/',
                'tag': 'user_detail',
            },
            {
                'method': 'GET',
                'uri': '/v1/users/index/surname/',
                'tag': 'user_alphabet_index',
            },
            # todo: /v1/users/me/

            # ping
            {
                'method': 'GET',
                'uri': '/ping',
                'tag': 'ping',
            },
            {
                'method': 'GET',
                'uri': '/ping/',
                'tag': 'ping',
            },
        ]
