import os

from django.db import migrations


def move_files(apps, schema_editor):
    CsvDataSource = apps.get_model('csvdatasource', 'CsvDataSource')
    CsvDataSource.get_connector_slug = lambda *args, **kwargs: 'csvdatasource'
    for instance in CsvDataSource.objects.all():
        old_name = instance.csv_file.name
        old_path = instance.csv_file.path
        if not old_name.startswith('csv/'):
            continue
        if not os.path.exists(old_path):
            continue
        filename = os.path.basename(old_name)
        instance.csv_file.save(filename, instance.csv_file)
        os.unlink(old_path)


class Migration(migrations.Migration):

    dependencies = [
        ('csvdatasource', '0019_csv_upload_to'),
    ]

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