from library.python import resource
from jinja2 import Template
import yaml


class ConfigManager:
    def __init__(self):
        return

    @property
    def common_upstream_template(self):
        res = resource.find('saas/library/python/awacs/upstream_common_config.yaml').decode("utf-8")
        return Template(res)

    @property
    def common_backend_template(self):
        res = resource.find('saas/library/python/awacs/backend_common_config.yaml').decode("utf-8")
        return Template(res)

    def render_upstream_config(self, backends, namespace_id, ctype=None, service=None, upstream_type="service", owners=None, on_last_failed_retry=None, connect_timeout="40ms",
                               balancer_attempts_num=2, backend_timeout="3s", max_reattempts_share=0.1, max_pessimized_endpoints_share=0.3,
                               dc_balancer_attempts_num=2, weights_section_id="default", retry_responses=False, ferryman_name=None, dc_balancer_method="BY_DC_WEIGHT",
                               order_label=None, author=None):
        if owners is None:
            owners = ['coffeeman', 'i024', 'salmin']
        return yaml.safe_load(self.common_upstream_template.render(author=author, backends=backends, upstream_type=upstream_type,
                                                                   owners=owners, ferryman_name=ferryman_name, balancer_attempts_num=balancer_attempts_num,
                                                                   connect_timeout=connect_timeout, namespace_id=namespace_id, backend_timeout=backend_timeout,
                                                                   max_reattempts_share=max_reattempts_share, dc_balancer_method=dc_balancer_method,
                                                                   max_pessimized_endpoints_share=max_pessimized_endpoints_share, order_label=order_label,
                                                                   dc_balancer_attempts_num=dc_balancer_attempts_num, weights_section_id=weights_section_id,
                                                                   ctype=ctype, service=service, retry_responses=retry_responses, on_last_failed_retry=on_last_failed_retry))

    def render_backend_config(self, backend_id, namespace_id, owners=None, author=None, backend_type="YP_ENDPOINT_SETS_SD", dc=None, endpoint_set_id=None, service_id=None):
        if owners is None:
            owners = ['coffeeman', 'i024', 'salmin']
        return yaml.safe_load(self.common_backend_template.render(author=author, owners=owners, backend_id=backend_id,
                                                                  namespace_id=namespace_id, backend_type=backend_type, dc=dc,
                                                                  endpoint_set_id=endpoint_set_id, service_id=service_id))
