# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-04-03 10:50
from __future__ import unicode_literals

import os
import shutil

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


class PanoramaRebuilder:

    STORE_DIR_NAME = 'panorama_store'

    def __init__(self, obj):
        self.obj = obj

    @property
    def old_path(self):
        return os.path.join(
            settings.MEDIA_ROOT, self.STORE_DIR_NAME, self.obj.slug)

    @property
    def new_path(self):
        return os.path.join(
            settings.MEDIA_ROOT, self.STORE_DIR_NAME, str(self.obj.id))

    def reorg(self):
        if not os.path.isdir(self.old_path):
            return

        os.rename(self.old_path, self.new_path)

        indexdata = os.path.join(self.new_path, 'indexdata')
        os.makedirs(indexdata)

        for basename in os.listdir(self.new_path):
            if basename.split('.')[-1] == 'html':
                continue
            pathname = os.path.join(self.new_path, basename)
            shutil.move(pathname, indexdata)


def reogr_files(apps, schema_editor):
    PanoramaStore = apps.get_model('panoramas', 'PanoramaStore')
    for pano in PanoramaStore.objects.iterator():
        PanoramaRebuilder(pano).reorg()


class Migration(migrations.Migration):

    dependencies = [
        ('panoramas', '0003_auto_20170403_1305'),
    ]

    operations = [
        migrations.RunPython(reogr_files, migrations.RunPython.noop),
    ]
