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_processing(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 'cs-search' not in self.select_components: self.get_external_class(cs_searchapi)
        if self.DETALIZATION < 5 and self.DETALIZATION > 2: self.CS_REGISTRY_HOST.append(self.CS_FILESTORAGE_HOST[-1])
        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-processing.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": ('CS_PROCESSING_IMAGE_NAME','CS_PROCESSING_IMAGE_VERSION'),
                "default": f"{self.CS_PROCESSING_IMAGE_NAME[0]}:{self.CS_PROCESSING_IMAGE_VERSION[0]}",
                "enable": None,
                "msg": (
                    f'Р7-Корпоративный сервер:\n\nВведите имя docker-образа в формате image:tag для службы Processing',
                    f'Имя обязательно к заполнению.',
                    f'Имя docker-образа не может содержать спецсимволы, кроме "-", "." и ":"'
                ),
                "func_parse": self.parse_image_tag(),
                "func_check": self.check_image_tag(),
                "func_visibility": self.visibility_detalization(),
                "detalization": 6
            },
            {
                "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
            }
        ];
        self.get_dialogs(dialogs)


    def add_service(self):
        self.env_is_default([
            'CS_PROCESSING_IMAGE_NAME',
            'CS_PROCESSING_IMAGE_VERSION',
            'CS_PROCESSING_CONTAINER_NAME',
            'CS_PROCESSING_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_registry_addr': f'http://{self.CS_REGISTRY_HOST[-1]}:{self.CS_REGISTRY_PORT[-1]}',
                    'r7_searchapi_addr': f'http://{self.CS_SEARCH_HOST[-1]}:{self.CS_SEARCH_PORT[-1]}',
                    '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]
                },
                'volumes':[
                    {'type': 'bind', 'source': f'{sys.path[0]}/configs/processing/filestorage.json', 'target': '/opt/r7-office/Processing/filestorage.json'},
                    {'type': 'bind', 'source': f'{sys.path[0]}/configs/processing/filestorage_temp', 'target': '/var/r7-office/filestorage_temp_proc/'},
                    {'type': 'bind', 'source': f'{sys.path[0]}/configs/processing/appsettings.json', 'target': '/opt/r7-office/Processing/appsettings.json'},
                    {'type': 'bind', 'source': f'{sys.path[0]}/configs/processing/services.json', 'target': '/opt/r7-office/Processing/services.json'},
                    {'type': 'bind', 'source': f'{sys.path[0]}/configs/processing/nlog.config', 'target': '/opt/r7-office/Processing/nlog.config'},
                    {'type': 'bind', 'source': f'{self.GENERAL_NODE_LOGS_STORAGE[-1]}/processing', 'target': '/var/log/r7-office/CDDisk/R7.Storage.Server.Processing.Host'}
                ],
                'networks': [f'net-{self.PREFIX_CS[0]}',f'net-{self.PREFIX_DS[0]}',f'net-{self.PREFIX_MAIL[0]}'],
#                'networks': [f'net-{self.PREFIX_CS[0]}'],
                'image': f'{self.CS_PROCESSING_IMAGE_NAME[-1]}:{self.CS_PROCESSING_IMAGE_VERSION[-1]}',
                'container_name': self.CS_PROCESSING_CONTAINER_NAME[-1],
                'hostname': self.CS_PROCESSING_HOST[-1],
                'restart': 'unless-stopped',
                'depends_on': ['cs-registry','cs-searchapi','cs-filestorage','cs-rabbitmq','cs-postgres']
            }
        };

