import sys

from .base_service import Base_service
from .cs_rabbitmq import cs_rabbitmq
from .cs_postgres import cs_postgres
from .cs_filestorage import cs_filestorage
from .cs_searchapi import cs_searchapi
from .cs_registry import cs_registry

class cs_ssoapi(Base_service):

    def go(self, **kwarg):
        if 'cs-rabbitmq' not in self.select_components: self.get_external_class(cs_rabbitmq)
        if 'cs-postgres' not in self.select_components: self.get_external_class(cs_postgres)
        if 'cs-filestorage' not in self.select_components: self.get_external_class(cs_filestorage)
        if ((self.DETALIZATION) < 5 and (self.DETALIZATION > 2)): self.CS_REGISTRY_HOST.append(self.CS_FILESTORAGE_HOST[-1])
        if 'cs-search' not in self.select_components: self.get_external_class(cs_searchapi)
        if 'cs-registry' not in self.select_components: self.get_external_class(cs_registry)
        self.async_runner(tasks=[self.load_images_async, self.get_requests], images=['cddisk-ssoapi.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'GENERAL_NODE_LOGS_STORAGE',
                "enable": None,
                'msg': (
                    f'Р7-Корпоративный сервер:\n\nВведите путь до директории хранения логов',
                    f'Путь до директории хранения логов обязателен к заполнению',
                    f'Указанный путь не найден'
                ),
                "func_parse": self.parse_path_dir(),
                "func_check": self.check_extended_dir(),
                "func_visibility": self.visibility_detalization(),
                "detalization": 2
            },
            {
                "env": f'CS_SSO_HOST',
                "enable": None,
                "msg": (
                    f'Р7-Корпоративный сервер:\n\nВведите адрес {"внешней " if external else ""}службы SsoApi',
                    f'Адрес {"внешней " if external else ""}службы SsoApi обязателен к заполнению.',
                    f'Адрес {"внешней " if external else ""}службы SsoApi не может содержать спецсимволы, кроме "-" и "."'
                ),
                "func_check": self.check_hostname(),
                "func_visibility": self.visibility_detalization(),
                "detalization": 4
            },
            {
                "env": f'CS_SSO_PORT',
                "enable": None,
                "msg": (
                    f'Р7-Корпоративный сервер:\n\nВведите открытый номер порта {"внешней " if external else ""}службы SsoApi',
                    f'Номер порта {"внешней " if external else ""}службы SsoApi обязателен к заполнению.',
                    f'Номер порта {"внешней " if external else ""}службы SsoApi должен состоять из чисел, буквы и спецсимволы не допустимы.'
                ),
                "func_check": self.check_port(),
                "func_visibility": self.visibility_detalization(),
                "detalization": 5
            },            
        ];
        self.get_dialogs(dialogs)



    def add_service(self):
        self.env_is_default([
            'CS_SSO_IMAGE_NAME',
            'CS_SSO_IMAGE_VERSION',
            'CS_SSO_CONTAINER_NAME',
            'CS_SSO_HOST',
            'CS_SSO_IDP_METADATA',
            'CS_SSO_ISSUER',
            'CS_SSO_SIGN_CERT',
            'CS_SSO_SIGN_CERT_PWD',
            'CS_SSO_CERT_VALID_MODE',
            'CS_SSO_REVOCATION_MODE'
        ]);

        self.service = {self.__class__.__name__.replace('_','-'): {
                'environment':{
                    'r7_rabbitmq_host': self.CS_RABBIT_HOST[-1],
                    'r7_rabbitmq_user': self.CS_RABBIT_USER[-1],
                    'r7_rabbitmq_pass': self.CS_RABBIT_PWD[-1],
                    'r7_db_host':self.CS_PSQL_HOST[-1],
                    'r7_db_port': self.CS_PSQL_PORT[-1],
                    'r7_db_name': self.CS_PSQL_DB[-1],
                    'r7_db_user': self.CS_PSQL_USER[-1],
                    'r7_db_pass': self.CS_PSQL_PWD[-1],
                    'r7_sso_ipd_metadata': self.CS_SSO_IDP_METADATA[-1],
                    'r7_sso_issuer': self.CS_SSO_ISSUER[-1],
                    'r7_sso_sign_cert_file': self.CS_SSO_SIGN_CERT[-1],
                    'r7_sso_sign_cert_pass': self.CS_SSO_SIGN_CERT_PWD[-1],
                    'r7_sso_cert_valid_mode': self.CS_SSO_CERT_VALID_MODE[-1],
                    'r7_sso_revocation_mode': self.CS_SSO_REVOCATION_MODE[-1],
                    'r7_registry_addr': f'http://{self.CS_REGISTRY_HOST[-1]}:{self.CS_REGISTRY_PORT[-1]}'
                },
                'volumes':[
                    {'type': 'bind', 'source': f'{sys.path[0]}/configs/ssl', 'target': '/opt/r7-office/Sso.Api/ssl'},
                    {'type': 'bind', 'source': f'{sys.path[0]}/configs/ssoapi/appsettings.json', 'target': '/opt/r7-office/Sso.Api/appsettings.json'},
                    {'type': 'bind', 'source': f'{sys.path[0]}/configs/ssoapi/nlog.config', 'target': '/opt/r7-office/Sso.Api/nlog.config'},
                    {'type': 'bind', 'source': f'{self.GENERAL_NODE_LOGS_STORAGE[-1]}/ssoapi', 'target': '/var/log/r7-office/CDDisk/R7.Sso.Api.Host'}
                ],
                'networks': [f'net-{self.PREFIX_CS[0]}'],
                'image': f'{self.CS_SSO_IMAGE_NAME[-1]}:{self.CS_SSO_IMAGE_VERSION[-1]}',
                'container_name': self.CS_SSO_CONTAINER_NAME[-1],
                'hostname': self.CS_SSO_HOST[-1],
                'restart': 'unless-stopped',
                'depends_on': ['cs-registry','cs-rabbitmq','cs-postgres']
            }
        };


