# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-05 20:22
from __future__ import unicode_literals

from django.db import migrations
from django.utils.translation import gettext

from pretix.base.i18n import language


def convert_old_settings(app, schema_editor):
    EventSettingsStore = app.get_model('pretixbase', 'Event_SettingsStore')
    for es in EventSettingsStore.objects.filter(key='ticketoutput_pdf_layout'):
        locale_es = EventSettingsStore.objects.filter(object=es.object, key='locale').first()
        if locale_es:
            locale = locale_es.value
        else:
            locale = 'en'

        with language(locale):
            es.object.ticket_layouts.create(
                name=gettext('Default layout'),
                default=True,
                layout=es.value
            )

    for es in EventSettingsStore.objects.filter(key='ticketoutput_pdf_background'):
        locale_es = EventSettingsStore.objects.filter(object=es.object, key='locale').first()
        if locale_es:
            locale = locale_es.value
        else:
            locale = 'en'

        with language(locale):
            l = es.object.ticket_layouts.get_or_create(
                default=True,
                defaults={
                    'name': gettext('Default layout'),
                }
            )[0]

            l.background.name = es.value[7:]
            setattr(l, 'background', l.background.name)
            l.save()
            es.delete()


class Migration(migrations.Migration):

    dependencies = [
        ('ticketoutputpdf', '0001_initial'),
    ]

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