# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-12-19 10:34
from __future__ import unicode_literals

from django.conf import settings as django_settings
from django.db import migrations, models
import django.db.models.deletion

from molo.core.models import CmsSettings, Timezone

from pytz import common_timezones

from wagtail.wagtailcore.models import Site


def seed_timezones(apps, schema_editor):
    for timezone_title in common_timezones:
        timezone = Timezone.objects.create(title=timezone_title)
        timezone.save()


def delete_timezones(apps, schema_editor):
    Timezone.objects.all().delete()


def set_initial_timezone(apps, schema_editor):
    current_timezone_name = django_settings.TIME_ZONE or 'UTC'
    for site in Site.objects.all():
        cms_settings = CmsSettings.for_site(site)
        cms_settings.timezone = Timezone.objects.filter(
            title=current_timezone_name,
        ).first()
        cms_settings.save()


def unset_timezone(apps, schema_editor):
    for site in Site.objects.all():
        site_settings = CmsSettings.for_site(site)
        site_settings.timezone = None
        site_settings.save()


class Migration(migrations.Migration):

    dependencies = [
        ('wagtailcore', '0040_page_draft_title'),
        ('core', '0074_banner_subtitle'),
    ]

    operations = [
        migrations.CreateModel(
            name='CmsSettings',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('site', models.OneToOneField(editable=False, on_delete=django.db.models.deletion.CASCADE, to='wagtailcore.Site')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Timezone',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=255, unique=True)),
            ],
        ),
        migrations.AddField(
            model_name='cmssettings',
            name='timezone',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='core.Timezone'),
        ),
        migrations.RunPython(seed_timezones, delete_timezones),
        migrations.RunPython(set_initial_timezone, unset_timezone),
    ]
