from saas.tools.devops.lib23.deploy_manager_api import DeployManagerApiClient
from saas.tools.devops.lib23.saas_slot import Slot
# from saas.library.python.bundle_networks import BundleNetworks


class SaaSCtype:

    DM = None

    def __init__(self, name):

        self.name = name
        if self.DM is None:
            self.DM = DeployManagerApiClient()

        self.golovan_prj = self.name.replace('stable', 'saas', 1).replace('_', '-')

    def get_searchproxies(self):
        proxies = self.DM.get_slots_and_stats(
            ctype=self.name,
            service='searchproxy',
            # service_type='searchproxy'
        )['slots']
        return proxies

    def get_all_proxies_from_dc(self, dc):
        proxies = []
        for proxy in self.get_searchproxies():
            if proxy["$datacenter$"].lower() == dc.lower():
                proxies.append(proxy)
        return proxies

    def get_random_proxy_from_dc(self, dc):
        for proxy in self.get_searchproxies():
            if proxy["$datacenter$"].lower() == dc.lower():
                return proxy
        return None

    def get_proxy_instance(self):
        for proxy in self.get_searchproxies():
            proxy_instance = Slot(proxy['id'])
            if not proxy_instance.is_down:
                return proxy_instance
        return proxy_instance

    @property
    def golovan_prj_prefix(self):
        if self.name.startswith('prestable'):
            return self.name.replace('prestable', 'saas-pre', 1).replace('_', '-')
        else:
            return self.name.replace('stable', 'saas', 1).replace('_', '-')

    @property
    def nanny_default_category(self):
        if self.name == 'testing':
            return 'testing'
        elif self.name == 'prestable':
            return 'prestable'
        elif self.name in ['stable', 'stable_kv', 'stable_middle_kv']:
            return 'stable'
        elif self.name == ['stable_hamster']:
            return 'stable_hamster'

        else:
            for prefix in ['stable_hamster', 'stable', 'prestable']:
                if self.name.startswith(prefix):
                    return self.name.replace(prefix, '', 1).strip('_')
        return 'other'

    @property
    def saas_debug_proxy_tvm_id(self):
        if self.name.startswith('prestable'):
            return 2010902
        else:
            return 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())
