# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import math
from library.python import resource
from jinja2 import Environment

REQUESTS_PER_PROXY = {
    'stable': 1500,
    'stable_kv': 5000,
    'stable_market': 6000,
    'stable_middle_kv': 4500,
}


def get_nominal_proxy_capacity(ctype):
    return REQUESTS_PER_PROXY.get(ctype, 1500)


def render_config(ctype, service, targets, ticket, user, schedule, timing_threshold=None, headers=None):
    if len(targets) < 1:
        raise RuntimeError('Empty target list')
    else:
        target = targets[0]
        additional_targets = targets[1:]

    config_template_string = resource.find('/saas/tank_config_template')
    jinja2_environment = Environment(trim_blocks=False, lstrip_blocks=False, keep_trailing_newline=True)
    template = jinja2_environment.from_string(config_template_string.decode('utf-8'))
    return template.render(
        target=target, additional_targets=additional_targets, all_targets=targets, schedule=schedule, ticket=ticket,
        operator=user, timing_treshold=timing_threshold, ctype=ctype, service=service, headers=headers
    )


def build_tank_config(ctype, service, targets, ticket, user,
                      target_rps, timing_threshold=None, line_duration='5m', const_duration='5m', headers=None):

    per_target_rps = int(math.ceil(target_rps/float(len(targets))))
    schedule = 'line(1,{rps},{line_duration}) const({rps},{const_duration})'.format(
        rps=per_target_rps, line_duration=line_duration, const_duration=const_duration
    )

    if headers:
        headers = "[{}]".format(', '.join(["'{}'".format(header) for header in headers]))
    return render_config(ctype, service, targets, ticket, user, schedule, timing_threshold, headers)
