# coding: utf-8


import io
import logging
import os

from django.conf import settings
from django.core.management.base import AppCommand, CommandError
from django.db import connection

from idm.utils.i18n import set_translation

log = logging.getLogger(__name__)


class Command(AppCommand):
    help = """Загружает sql-файлы для unmanaged-моделей аналогично тому, как это делало Django <= 1.8"""

    @set_translation
    def handle_app_config(self, app_config, **options):
        verbosity = options.get('verbosity')
        if app_config.models_module is None:
            raise CommandError('Application %s has no models module' % app_config.name)
        sql_filenames = [
            'sql_%s.sql' % model._meta.model_name
            for model in app_config.get_models()
            if model._meta.managed is False or model.__name__ in settings.IDM_SQL_FOR_MODELS
        ]
        sql_filenames += [
            'def_%s.sql' % procedure
            for procedure in settings.IDM_SQL_PROCEDURES
        ]
        if not sql_filenames:
            raise CommandError('Application %s has no unmanaged models' % app_config.name)
        sql_path = os.path.normpath(os.path.join(app_config.path, 'sql'))
        executed = 0
        for sql_filename in sql_filenames:
            sql_file = os.path.join(sql_path, sql_filename)
            if os.path.exists(sql_file):
                with io.open(sql_file, encoding='utf-8') as fp:
                    statements = connection.ops.prepare_sql_script(fp.read())
                    with connection.cursor() as cursor:
                        for statement in statements:
                            cursor.execute(statement)
                            if verbosity > 1:
                                log.info('Executing SQL statement for model %s: %s', model._meta.model_name, statement)
                            executed += 1
        if verbosity != 0:
            log.info('%d sql statements executed', executed)
