# Generated by Django 2.2.17 on 2020-12-06 14:07
import os
from pathlib import Path

from django.conf import settings
from django.db import migrations
from django.utils import timezone


class Tee:
    def __init__(self, f):
        self.f = f

    def __enter__(self):
        return self

    def __call__(self, line):
        if not isinstance(line, str):
            line = str(line)
        print(line)
        self.f.write(line)
        self.f.write('\n')

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass


def forward_code(apps, schema_editor):
    ItemImageModel = apps.get_model('inventory', 'ItemImageModel')
    if ItemImageModel.objects.count() == 0:
        # No image uploaded, yet -> nothing to do
        return

    print()
    log_file_path = Path(settings.MEDIA_ROOT, 'migrate.log')
    print('Generate log file here:', log_file_path)
    with log_file_path.open('w+') as log, Tee(log) as log:
        log('-' * 100)
        log(timezone.now())

        from django_tools.serve_media_app.models import generate_media_path

        qs = ItemImageModel.objects.all()

        for instance in qs:
            log('_' * 100)
            log(f'Migrate {instance}')
            user = instance.user
            image = instance.image

            file_path = Path(str(image.file))
            log(f'Old path: {file_path}')

            media_path = generate_media_path(user, filename=file_path.name)

            new_file_path = Path(settings.MEDIA_ROOT, media_path)
            log(f'New path: {new_file_path}')

            os.makedirs(new_file_path.parent, exist_ok=True)
            os.link(file_path, new_file_path)

            instance.image = media_path
            instance.save(update_fields=('image',))

        log('All new path created via hardlinks!')
        log('Old path can be deleted.')


class Migration(migrations.Migration):
    dependencies = [
        ('inventory', '0004_item_user_images'),
        ('serve_media_app', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(forward_code, reverse_code=migrations.RunPython.noop),
    ]
