import sys
from .base_service import Base_service
from .cs_filestorage import cs_filestorage
from .cs_searchapi import cs_searchapi

class cs_registry(Base_service):

    def go(self, **kwarg):
        if 'cs-filestorage' not in self.select_components: self.get_external_class(cs_filestorage)
        if 'cs-searchapi' not in self.select_components: self.get_external_class(cs_searchapi)
        self.async_runner(tasks=[self.load_images_async, self.get_requests], images=['cddisk-registry.img'], **kwarg)
#        self.get_requests(**kwarg);
        self.add_service();

    async def get_requests(self, dialog: dict = None, external:bool = False, **kwarg):
        dialogs = dialog if isinstance(dialog, list) else [
            {
                "env": f'CS_REGISTRY_HOST',
                "enable": None,
                "msg": (
                    f'Р7-Корпоративный сервер:\n\nВведите адрес {"внешней " if external else ""}службы Registry',
                    f'Адрес {"внешней " if external else ""}службы Registry обязателен к заполнению.',
                    f'Адрес {"внешней " if external else ""}службы Registry не может содержать спецсимволы, кроме "-" и "."'
                ),
                "func_check": self.check_hostname(),
                "func_visibility": self.visibility_detalization(),
                "detalization": 3
            },
            {
                "env": f'CS_REGISTRY_PORT',
                "enable": None,
                "msg": (
                    f'Р7-Корпоративный сервер:\n\nВведите открытый номер порта {"внешней " if external else ""}службы Registry',
                    f'Номер порта {"внешней " if external else ""}службы Registry обязателен к заполнению.',
                    f'Номер порта {"внешней " if external else ""}службы Registry должен состоять из чисел, буквы и спецсимволы не допустимы.'
                ),
                "func_check": self.check_port(),
                "func_visibility": self.visibility_detalization(),
                "detalization": 5
            },
        ];
        self.get_dialogs(dialogs)
#        for request in dialogs:
#            if request["enable"]:
#                self.get_request(
#                    env_name = request["env"],
#                    msg = request['msg'],
#                    func_check = request["func_check"],
#                    password = request["env"].endswith("_PWD")
#                );
#            else:
#                if len(getattr(self, request["env"])) != 2: getattr(self, request["env"]).append(getattr(self, request["env"])[0]);

    def add_service(self):
        self.env_is_default([
            'CS_REGISTRY_IMAGE_NAME',
            'CS_REGISTRY_IMAGE_VERSION',
            'CS_REGISTRY_CONTAINER_NAME',
            'CS_REGISTRY_HOST'
        ]);

        self.service = {self.__class__.__name__.replace('_','-'): {
                'environment':{
                    'r7_filestorage_host': self.CS_FILESTORAGE_HOST[-1],
                    'r7_filestorage_tcp_port': self.CS_FILESTORAGE_PORT_TCP[-1],
                    'r7_filestorage_http_port': self.CS_FILESTORAGE_PORT_HTTP[-1],
                    'r7_searchapi_addr': f'http://{self.CS_SEARCH_HOST[-1]}:{self.CS_SEARCH_PORT[-1]}'
                },
                'volumes':[
                    {'type': 'bind', 'source': f'{sys.path[0]}/configs/serviceregistry/appsettings.json', 'target': '/opt/r7-office/Service.Registry/appsettings.json'}
                ],
                'networks': [f'net-{self.PREFIX_CS[0]}'],
                'image': f'{self.CS_REGISTRY_IMAGE_NAME[-1]}:{self.CS_REGISTRY_IMAGE_VERSION[-1]}',
                'container_name': self.CS_REGISTRY_CONTAINER_NAME[-1],
                'hostname': self.CS_REGISTRY_HOST[-1],
                'restart': 'unless-stopped',
                'depends_on': ['cs-filestorage','cs-searchapi']
            }
        };
