# Generated by Django 3.2.15 on 2022-11-20 14:20

from django.apps import apps
import aleksis.core.managers
from django.db import migrations, models
from django.db.utils import ProgrammingError
import django.db.models.deletion
import django.utils.timezone
import oauth2_provider.generators
import oauth2_provider.models
from psycopg2.errors import UndefinedTable


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0046_notification_create_field_icon'),
    ]

    # This migration must run after Chronos' migration 1 through 12, but before
    #  13. That's because we are in fact moving a model, and we need to make sure
    #  that this migration runs at the right time.
    if "chronos" in apps.app_configs:
        recorder = migrations.recorder
        applied = False
        try:
            applied = recorder.MigrationRecorder.Migration.objects.filter(app="core", name="0047_add_room_model").exists()
        except ProgrammingError:
            applied = False
        if not applied:
            dependencies.append(('chronos', '0012_add_supervision_global_permission'))

    operations = [
        migrations.CreateModel(
            name='Room',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('extended_data', models.JSONField(default=dict, editable=False)),
                ('short_name', models.CharField(max_length=255, verbose_name='Short name')),
                ('name', models.CharField(max_length=255, verbose_name='Long name')),
            ],
            options={
                'verbose_name': 'Room',
                'verbose_name_plural': 'Rooms',
                'ordering': ['name', 'short_name'],
                'permissions': (('view_room_timetable', 'Can view room timetable'),),
            },
            managers=[
                ('objects', aleksis.core.managers.AlekSISBaseManager()),
            ],
        ),
        migrations.AddConstraint(
            model_name='room',
            constraint=models.UniqueConstraint(fields=('short_name',), name='unique_room_short_name_per_site'),
        ),
        # Migrate data from Chronos table; deletion will be handled by Chronos
        migrations.RunSQL(
            """
            -- Copy rooms from chronos if table exists
            DO $$BEGIN INSERT INTO core_room SELECT * FROM chronos_room; EXCEPTION WHEN undefined_table THEN NULL; END$$;
            """
        ),
    ]
