# Generated by Django 3.2.7 on 2021-10-01 22:34

import datetime
from datetime import timedelta

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
from django.utils import timezone
from django.utils.timezone import utc
from django_scopes import scopes_disabled

from cookbook.models import FoodInheritField, ShoppingListEntry


def delete_orphaned_sle(apps, schema_editor):
    with scopes_disabled():
        # shopping list entry is orphaned - delete it
        ShoppingListEntry.objects.filter(shoppinglist=None).delete()


def create_inheritfields(apps, schema_editor):
    FoodInheritField.objects.create(name='Supermarket Category', field='supermarket_category')
    FoodInheritField.objects.create(name='On Hand', field='food_onhand')
    FoodInheritField.objects.create(name='Diet', field='diet')
    FoodInheritField.objects.create(name='Substitute', field='substitute')
    FoodInheritField.objects.create(name='Substitute Children', field='substitute_children')
    FoodInheritField.objects.create(name='Substitute Siblings', field='substitute_siblings')


def set_completed_at(apps, schema_editor):
    today_start = timezone.now().replace(hour=0, minute=0, second=0)
    # arbitrary - keeping all of the closed shopping list items out of the 'recent' view
    month_ago = today_start - timedelta(days=30)
    with scopes_disabled():
        ShoppingListEntry.objects.filter(checked=True).update(completed_at=month_ago)


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('cookbook', '0159_add_shoppinglistentry_fields'),
    ]

    operations = [
        migrations.RunPython(delete_orphaned_sle),
        migrations.RunPython(create_inheritfields),
        migrations.RunPython(set_completed_at),
    ]
