# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-08-18 12:02
from __future__ import unicode_literals

import os

import django.db.models.deletion
from django.contrib.contenttypes.models import ContentType
from django.db import migrations, models


def move_old_jenkins_checks(apps, schema_editor):
    db_alias = schema_editor.connection.alias

    JenkinsStatusCheck = apps.get_model("cabotapp", "JenkinsStatusCheck")
    JenkinsCheck = apps.get_model("cabotapp", "JenkinsCheck")
    JenkinsConfig = apps.get_model("cabotapp", "JenkinsConfig")

    # Due to a polymorphic bug, JenkinsStatusCheck actually returns all status checks
    # Use this to filter out the other checks.
    jenkins_content_type = ContentType.objects.filter(model="jenkinsstatuscheck").first()

    if jenkins_content_type and not JenkinsStatusCheck.objects.filter(polymorphic_ctype_id=jenkins_content_type.id).exists():
        return

    if not JenkinsConfig.objects.exists():
        JenkinsConfig.objects.create(
            name="Default Jenkins",
            jenkins_api=os.environ.get("JENKINS_API", "http://jenkins.example.com"),
            jenkins_user=os.environ.get("JENKINS_USER", ""),
            jenkins_pass=os.environ.get("JENKINS_PASS", ""),
        )

    default_config = JenkinsConfig.objects.first()

    for old_check in JenkinsStatusCheck.objects.all():
        if old_check.polymorphic_ctype_id != jenkins_content_type.id:
            continue
        new_check = JenkinsCheck(
            active=old_check.active,
            allowed_num_failures=old_check.allowed_num_failures,
            cached_health=old_check.cached_health,
            calculated_status=old_check.calculated_status,
            check_type=old_check.check_type,
            created_by_id=old_check.created_by_id,
            debounce=old_check.debounce,
            endpoint=old_check.endpoint,
            expected_num_hosts=old_check.expected_num_hosts,
            frequency=old_check.frequency,
            importance=old_check.importance,
            last_run=old_check.last_run,
            max_queued_build_time=old_check.max_queued_build_time,
            metric=old_check.metric,
            name=old_check.name,
            password=old_check.password,
            status_code=old_check.status_code,
            text_match=old_check.text_match,
            timeout=old_check.timeout,
            username=old_check.username,
            value=old_check.value,
            jenkins_config=default_config,
            # For some reason this isn't handled automatically...
            # The model is renamed in the next migration so the ctype
            # id stays consistent.
            polymorphic_ctype_id=old_check.polymorphic_ctype_id
        )
        new_check.save(using=db_alias)
        new_check.service_set.add(*old_check.service_set.all())
        new_check.instance_set.add(*old_check.instance_set.all())
        new_check.save(using=db_alias)
        old_check.delete(using=db_alias)


class Migration(migrations.Migration):

    dependencies = [
        ('cabotapp', '0004_auto_20170802_1327'),
    ]

    operations = [
        migrations.CreateModel(
            name='JenkinsCheck',
            fields=[
                ('statuscheck_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='cabotapp.StatusCheck')),
            ],
            options={
                'abstract': False,
            },
            bases=('cabotapp.statuscheck',),
        ),
        migrations.CreateModel(
            name='JenkinsConfig',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=30)),
                ('jenkins_api', models.CharField(max_length=2000)),
                ('jenkins_user', models.CharField(max_length=2000)),
                ('jenkins_pass', models.CharField(max_length=2000)),
            ],
        ),
        migrations.AddField(
            model_name='jenkinscheck',
            name='jenkins_config',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cabotapp.JenkinsConfig'),
        ),
        migrations.RunPython(move_old_jenkins_checks)
    ]
