# Generated by Django 3.2.15 on 2023-05-19 11:57

import django.core.serializers.json
from django.db import migrations, models
import django.db.models.deletion
import nautobot.extras.models.mixins
import taggit.managers
import uuid
from django.db.migrations.recorder import MigrationRecorder
from django.contrib.contenttypes.models import ContentType

_APP_LABEL = "nautobot_chatops"
_OLD_APP_LABEL = "nautobot_plugin_chatops_grafana"
_MODEL_NAMES = ["Dashboard", "Panel", "PanelVariable"]


def _copy(model_name, apps, connection):
    new_model_name = f"grafana{model_name.lower()}"
    new_model = apps.get_model(_APP_LABEL, new_model_name)
    new_table_name = new_model._meta.db_table
    old_table_name = new_table_name.replace(f"{_APP_LABEL}_grafana", f"{_OLD_APP_LABEL}_")

    with connection.cursor() as cursor:
        # Table names are from trusted source (this script)
        cursor.execute(f"INSERT INTO {new_table_name} SELECT * FROM {old_table_name};")  # nosec

    # Update the content type to point to the new model
    old_content_type = ContentType.objects.get(app_label=_OLD_APP_LABEL, model=model_name.lower())
    old_content_type.app_label = _APP_LABEL
    old_content_type.model = new_model_name
    old_content_type.save()


def _delete(model_name, connection):
    old_table_name = f"{_OLD_APP_LABEL}_{model_name}"
    with connection.cursor() as cursor:
        cursor.execute(f"DROP TABLE {old_table_name} CASCADE;")


def _move_data(apps, schema_editor):
    old_migration = {
        "app": _OLD_APP_LABEL,
        "name": "0001_initial",
    }
    if MigrationRecorder.Migration.objects.filter(**old_migration).exists():
        for name in _MODEL_NAMES:
            _copy(name, apps, schema_editor.connection)
        for name in _MODEL_NAMES:
            _delete(name, schema_editor.connection)


class Migration(migrations.Migration):
    dependencies = [
        ("extras", "0047_enforce_custom_field_slug"),
        ("nautobot_chatops", "0004_remove_params_rename_params1"),
    ]

    operations = [
        migrations.CreateModel(
            name="GrafanaDashboard",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True
                    ),
                ),
                ("created", models.DateField(auto_now_add=True, null=True)),
                ("last_updated", models.DateTimeField(auto_now=True, null=True)),
                (
                    "_custom_field_data",
                    models.JSONField(blank=True, default=dict, encoder=django.core.serializers.json.DjangoJSONEncoder),
                ),
                ("dashboard_slug", models.CharField(max_length=255, unique=True)),
                ("friendly_name", models.CharField(blank=True, default="", max_length=255)),
                ("dashboard_uid", models.CharField(max_length=64, unique=True)),
                ("tags", taggit.managers.TaggableManager(through="extras.TaggedItem", to="extras.Tag")),
            ],
            options={
                "ordering": ["dashboard_slug"],
            },
            bases=(
                models.Model,
                nautobot.extras.models.mixins.DynamicGroupMixin,
                nautobot.extras.models.mixins.NotesMixin,
            ),
        ),
        migrations.CreateModel(
            name="GrafanaPanel",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True
                    ),
                ),
                ("created", models.DateField(auto_now_add=True, null=True)),
                ("last_updated", models.DateTimeField(auto_now=True, null=True)),
                (
                    "_custom_field_data",
                    models.JSONField(blank=True, default=dict, encoder=django.core.serializers.json.DjangoJSONEncoder),
                ),
                ("command_name", models.CharField(max_length=64)),
                ("friendly_name", models.CharField(default="", max_length=64)),
                ("panel_id", models.IntegerField()),
                ("active", models.BooleanField(default=False)),
                (
                    "dashboard",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE, to="nautobot_chatops.grafanadashboard"
                    ),
                ),
            ],
            options={
                "ordering": ["command_name", "dashboard"],
            },
            bases=(
                models.Model,
                nautobot.extras.models.mixins.DynamicGroupMixin,
                nautobot.extras.models.mixins.NotesMixin,
            ),
        ),
        migrations.CreateModel(
            name="GrafanaPanelVariable",
            fields=[
                (
                    "id",
                    models.UUIDField(
                        default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True
                    ),
                ),
                ("created", models.DateField(auto_now_add=True, null=True)),
                ("last_updated", models.DateTimeField(auto_now=True, null=True)),
                (
                    "_custom_field_data",
                    models.JSONField(blank=True, default=dict, encoder=django.core.serializers.json.DjangoJSONEncoder),
                ),
                ("name", models.CharField(max_length=32)),
                ("friendly_name", models.CharField(max_length=64)),
                ("query", models.CharField(max_length=64)),
                ("includeincmd", models.BooleanField(default=False)),
                ("includeinurl", models.BooleanField(default=True)),
                ("modelattr", models.CharField(max_length=64)),
                ("value", models.TextField(max_length=64)),
                ("response", models.CharField(max_length=255)),
                (
                    "filter",
                    models.JSONField(blank=True, default=dict, encoder=django.core.serializers.json.DjangoJSONEncoder),
                ),
                ("positional_order", models.IntegerField(default=100)),
                (
                    "panel",
                    models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="nautobot_chatops.grafanapanel"),
                ),
            ],
            options={
                "ordering": ["name"],
            },
            bases=(
                models.Model,
                nautobot.extras.models.mixins.DynamicGroupMixin,
                nautobot.extras.models.mixins.NotesMixin,
            ),
        ),
        migrations.RunPython(_move_data),
    ]
