# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-01-03 19:31
from __future__ import unicode_literals

import os

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


def move_payloads(apps, schema_editor):
    DemodData = apps.get_model('base', 'DemodData')
    for demod in DemodData.objects.all():
        try:
            folder = 'payload_frames/{0}/{1}/{2}/'.format(demod.timestamp.year,
                                                          demod.timestamp.month,
                                                          demod.timestamp.day)
        except AttributeError:
            folder = 'payload_frames/{0}/{1}/{2}/'.format(now().year, now().month, now().day)
        fullpath = '{0}/{1}'.format(settings.MEDIA_ROOT, folder)
        if not os.path.exists(fullpath):
            os.makedirs(fullpath)
        filename = demod.payload_frame.name.split('/')[-1]
        new_name = '{0}{1}'.format(folder, filename)
        new_path = '{0}/{1}'.format(settings.MEDIA_ROOT, new_name)
        os.rename(demod.payload_frame.path, new_path)
        demod.payload_frame.name = new_name
        demod.save()


class Migration(migrations.Migration):

    dependencies = [
        ('base', '0008_satellite_description'),
    ]

    operations = [
        migrations.RunPython(move_payloads),
    ]
