# Generated by Django 2.2.27 on 2023-08-21 14:50
import os
from django.db import migrations, models
from webodm import settings

def task_path(project_id, task_id, *args):
    return os.path.join(settings.MEDIA_ROOT,
                        "project",
                        str(project_id),
                        "task",
                        str(task_id),
                        *args)

def update_size(task):
    try:
        total_bytes = 0
        for dirpath, _, filenames in os.walk(task_path(task.project.id, task.id)):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                if not os.path.islink(fp):
                    total_bytes += os.path.getsize(fp)
        task.size = (total_bytes / 1024 / 1024)
        task.save()
        print("Updated {} with size {}".format(task, task.size))
    except Exception as e:
        print("Cannot update size for task {}: {}".format(task, str(e)))



def update_task_sizes(apps, schema_editor):
    Task = apps.get_model('app', 'Task')

    for t in Task.objects.all():
        update_size(t)

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0035_task_orthophoto_bands'),
    ]

    operations = [
        migrations.AddField(
            model_name='task',
            name='size',
            field=models.FloatField(blank=True, default=0.0, help_text='Size of the task on disk in megabytes', verbose_name='Size'),
        ),

        migrations.RunPython(update_task_sizes),
    ]
