from cached_property import cached_property_with_ttl
from six import ensure_str

from saas.library.python.deploy_manager_api import DeployManagerApiClient


class SaasCtype:
    _dm_client = DeployManagerApiClient()

    class Kind:
        PRESTABLE = 'prestable'
        HAMSTER = 'hamster'
        PROD = 'prod'

    PER_DC_PROXY_COUNT = {
        Kind.PRESTABLE: 2,
        Kind.HAMSTER: 3,
        Kind.PROD: 5
    }

    def __init__(self, name):
        self._name = name
        self._kind = self._parse_ctype(name)

    @property
    def name(self):
        return self._name

    @property
    def kind(self):
        return self._kind

    def _parse_ctype(self, name):
        if name.startswith(self.Kind.PRESTABLE):
            return self.Kind.PRESTABLE
        elif self.Kind.HAMSTER in name:
            return self.Kind.HAMSTER
        else:
            return self.Kind.PROD

    @property
    def yasm_prj_prefix(self):
        if self._kind == self.Kind.PRESTABLE:
            return self._name.replace('prestable', 'saas-pre', 1).replace('_', '-')
        else:
            return self._name.replace('stable', 'saas', 1).replace('_', '-')

    @property
    def proxy_instance_count(self):
        return self.PER_DC_PROXY_COUNT.get(self._kind, 5)

    @cached_property_with_ttl(ttl=30)
    def environment(self):
        file_content = self._dm_client.get_storage_file('common/{ctype}/environment'.format(ctype=self._name))
        file_text = ensure_str(file_content)

        result = {}
        for line in file_text.split('\n'):
            data = line.strip()
            if not data:
                continue

            key, value = data.split('=')
            result[key.strip()] = value.strip()
        return result

    @property
    def saas_debug_proxy_tvm_id(self):
        return 2010902 if self._kind == self.Kind.PRESTABLE else 2011468

    @property
    def backend_macro(self):
        return '_SAAS_{}_BASE_NETS_'.format(self.name.replace('-', '_').upper())

    @property
    def proxy_macro(self):
        return '_SAAS_{}_PROXY_NETS_'.format(self.name.replace('-', '_').upper())

    def __str__(self):
        return self._name

    def __repr__(self):
        return '{cls}({name})'.format(cls=self.__class__.__name__, name=self._name)
