# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-15 06:12
from __future__ import unicode_literals

import django.contrib.sites.models
from django.db import migrations
from django.contrib.contenttypes.management import create_contenttypes


def move_to_default(apps, schema_editor):
    Site = apps.get_model('sites', 'Site')
    Shard = apps.get_model('promgen', 'Shard')
    Rule = apps.get_model('promgen', 'Rule')
    Service = apps.get_model('promgen', 'Service')
    target = apps.get_model('contenttypes', 'ContentType').objects.get_for_model(Service)

    site = Site.objects.first()
    shard, _ = Shard.objects.get_or_create(name='Default')
    service, _ = Service.objects.get_or_create(name='Default', defaults={'shard': shard})

    for rule in Rule.objects.filter(object_id=site.id, content_type__model='site'):
        rule.content_type = target
        rule.object_id = service.id
        rule.save()


def move_to_global(apps, schema_editor):
    Site = apps.get_model('sites', 'Site')
    Shard = apps.get_model('promgen', 'Shard')
    Rule = apps.get_model('promgen', 'Rule')
    Service = apps.get_model('promgen', 'Service')
    target = apps.get_model('contenttypes', 'ContentType').objects.get_for_model(Site)

    site = Site.objects.first()
    shard, _ = Shard.objects.get_or_create(name='Default')
    service, _ = Service.objects.get_or_create(name='Default', defaults={'shard': shard})

    for rule in Rule.objects.filter(object_id=service.id, content_type__model='service'):
        rule.content_type = target
        rule.object_id = site.id
        rule.save()


class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
        ('sites', '0002_alter_domain_unique'),
        ('promgen', '0043_rule_description'),
    ]

    operations = [
        migrations.CreateModel(
            name='Site',
            fields=[
            ],
            options={
                'proxy': True,
                'indexes': [],
            },
            bases=('sites.site',),
            managers=[
                ('objects', django.contrib.sites.models.SiteManager()),
            ],
        ),
        migrations.RunPython(move_to_global, move_to_default, elidable=True,),
    ]
