import logging
import os
from pathlib import Path

from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.management.base import BaseCommand

from correlation.services.import_service import ImportRulesService
from incident.models import IncidentRecommendations

_log = logging.getLogger(__name__)


def create_addition():
    """
        During rules export, only those recommendations and effects that are used in the rules are exported.
        Here we manually create some objects that are not used anywhere in the rules
    """
    IncidentRecommendations.objects.get_or_create(name="Перевести работу АСУ ТП на резервный ПЛК",
                                                  description="Необходимо перевести работу на резервный ПЛК для "
                                                              "избежания нарушения технологического процесса.")


class Command(BaseCommand):
    help = 'Load default rules'

    def handle(self, *args, **options):
        rules_path = Path(os.path.abspath(__file__)).parents[0]
        with open(f'{rules_path}/rules_console.json', 'rb') as rule_file:
            file = SimpleUploadedFile("rules.json", rule_file.read())

            create_addition()
            import_service = ImportRulesService(file, check_version=False)
            import_service.run_import()
