# Generated by Django 2.0.3 on 2018-08-07 14:01

import datetime

import django.db.models.deletion
from django.db import migrations, models
from django.db.models import Q
from django.utils.text import slugify


def copy_featured_products_to_homepade_collection(apps, schema_editor):
    SiteSettings = apps.get_model("site", "SiteSettings")
    Collection = apps.get_model("product", "Collection")
    Product = apps.get_model("product", "Product")

    today = datetime.date.today()
    homepage_products = list(
        Product.objects.filter(
            Q(available_on__lte=today) | Q(available_on__isnull=True),
            is_published=True,
            is_featured=True,
        )
    )
    if homepage_products:
        homepage_collection = Collection(name="Homepage collection for migration")
        homepage_collection.slug = slugify(homepage_collection.name)
        homepage_collection.save()
        homepage_collection.products.add(*homepage_products)

        for site_setting in SiteSettings.objects.all():
            site_setting.homepage_collection = homepage_collection
            site_setting.save()


class Migration(migrations.Migration):

    dependencies = [
        ("product", "0066_auto_20180803_0528"),
        ("site", "0017_auto_20180803_0528"),
    ]

    operations = [
        migrations.AddField(
            model_name="sitesettings",
            name="homepage_collection",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="+",
                to="product.Collection",
            ),
        ),
        migrations.RunPython(
            copy_featured_products_to_homepade_collection,
            lambda app, schema_editor: None,
        ),
    ]
