# Generated by Django 3.2.12 on 2022-06-10 18:29

import os
import shutil

from django.db import migrations
from django.conf import settings
from cvat.apps.engine.log import get_logger

MIGRATION_NAME = os.path.splitext(os.path.basename(__file__))[0]
MIGRATION_LOG = os.path.join(settings.MIGRATIONS_LOGS_ROOT, f"{MIGRATION_NAME}.log")

def _get_query_set(apps):
    Job = apps.get_model("engine", "Job")
    query_set = Job.objects.all()
    return query_set

def _get_job_dir_path(jid):
    return os.path.join(settings.JOBS_ROOT, str(jid))

def create_directories(apps, schema_editor):
    logger = get_logger(MIGRATION_NAME, MIGRATION_LOG)
    query_set = _get_query_set(apps)
    logger.info(f'Migration has been started. Need to create {query_set.count()} directories.')

    for db_job in query_set:
        jid = db_job.id
        os.makedirs(_get_job_dir_path(jid), exist_ok=True)
    logger.info(f'Migration has been finished successfully.')

def delete_directories(apps, schema_editor):
    logger = get_logger(MIGRATION_NAME, MIGRATION_LOG)
    query_set = _get_query_set(apps)
    logger.info(f'Reverse migration has been started. Need to delete {query_set.count()} directories.')
    for db_job in query_set:
        jid = db_job.id
        job_dir = _get_job_dir_path(jid)
        if os.path.isdir(job_dir):
            shutil.rmtree(job_dir)
    logger.info(f'Migration has been reversed successfully.')

class Migration(migrations.Migration):

    dependencies = [
        ('engine', '0054_auto_20220610_1829'),
    ]

    operations = [
        migrations.RunPython(
            code=create_directories,
            reverse_code=delete_directories
        )
    ]
