# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-11-30 15:41
from __future__ import unicode_literals

from django.db import migrations, models
import os, pickle, tempfile

from webodm import settings

tasks = []
imageuploads = []
task_ids = {} # map old task IDs --> new task IDs


def restoreImageUploadFks(apps, schema_editor):
    global imageuploads, task_ids

    ImageUpload = apps.get_model('app', 'ImageUpload')
    Task = apps.get_model('app', 'Task')

    for img in imageuploads:
        i = ImageUpload.objects.get(pk=img['id'])
        old_image_path = i.image.name
        task_id = task_ids[img['task']]

        # project/2/task/5/DJI_0032.JPG --> project/2/task/<NEW_TASK_ID>/DJI_0032.JPG
        dirs, filename = os.path.split(old_image_path)
        head, tail = os.path.split(dirs)
        new_image_path = os.path.join(head, str(task_id), filename)

        i.task = Task.objects.get(id=task_id)
        i.image.name = new_image_path
        i.save()

        print("{} --> {} (Task {})".format(old_image_path, new_image_path, str(task_id)))


def restore(apps, schema_editor):
    global tasks, imageuploads, task_ids
    
    tmp_path = os.path.join(tempfile.gettempdir(), "public_task_uuids_migration.pickle")
    tasks, imageuploads, task_ids = pickle.load(open(tmp_path, 'rb'))


class Migration(migrations.Migration):

    dependencies = [
        ('app', '0014_public_task_uuids'),
    ]

    operations = [
        migrations.RunPython(restore),
        migrations.RunPython(restoreImageUploadFks),      
    ]
