# -*- coding: utf-8 -*-
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
from django.db import connections, transaction
from django.db.utils import DatabaseError

from events.common_app.utils import YLockCommandMixin
from events.arc_compat import read_asset


class MainCommand(BaseCommand):
    help = """ Удаляет все ContentTypes приложения, а также удаляет записи в south_migrationhistory
                Можно указать вторым параметром sql файл с запросами
            """
    args = '<app_label sql_file>'
    label = 'app_label'
    sql_file = 'sql_file'

    @transaction.atomic
    def handle(self, label, sql_file=None, **options):
        content_types = ContentType.objects.filter(app_label=label)
        cursor = connections['default'].cursor()
        for content_type in content_types:
            cursor.execute("DELETE FROM django_admin_log WHERE content_type_id={id}".format(id=str(content_type.id)))
            content_type.delete()
        cursor.execute("DELETE FROM south_migrationhistory WHERE app_name='{app}'".format(app=label))
        cursor.close()
        if sql_file:
            sql_file = read_asset(sql_file)
            for line in sql_file.readlines():
                try:
                    cursor = connections['default'].cursor()
                    cursor.execute(line)
                    cursor.close()
                except DatabaseError:
                    pass


class Command(YLockCommandMixin, MainCommand):
    lock_name = 'events.remove_application'
