# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-02-13 14:36
from __future__ import unicode_literals

from django.db import (
    connection,
    InternalError,
    migrations,
    models,
    ProgrammingError,
    DatabaseError,
)
from django.db import migrations, models


SQL = "ALTER TABLE journal_issue ADD COLUMN cached_display_title varchar(300) NULL"


def add_cached_display_title(apps, schema_editor):
    """Tries to add this column for installs affected by 22b1058

    https://github.com/birkbeckctp/janeway/commit/22b105843c9d030f43434813a6553f9d9361af6b
    This commit changed migration history, which has led installations to be in
    one of 2 main states.
     - Installations that migrated from 1.4.2 -> 1.4.3: unaffected
     - Installatio"ns that migrated from 1.4.2.1 -> 1.4.3: ProgramingError
    In order to solve this problem we have taken two actions:
     1. Move the AddField operation that adds `cached_displa_title` to
        migration journal.0051. This will allow the migration builder to not
        detect this missing state change on the models. New installations or
        installations upgrading from =<1.4.1 will run this operation
     2. Manually execute the SQL to add the column onto journal.0052 (this file)
        for installatations upgrading from 1.4.2.1 onto 1.4.3 (they would have
        missed the change above). New installations or installations coming
        directly from =<1.4.2 this will fail, so we handle the exception.
    """
    cursor = connection.cursor()
    try:
        cursor.execute(SQL)
    except (ProgrammingError, InternalError, DatabaseError) as err:
        # Column already exists
        pass


class Migration(migrations.Migration):
    dependencies = [
        ("submission", "0050_support_ordered_keywords"),
    ]


class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ("journal", "0051_journal_is_archived"),
    ]

    operations = [
        migrations.RunPython(
            add_cached_display_title, reverse_code=migrations.RunPython.noop
        ),
        migrations.AddField(
            model_name="fixedpubcheckitems",
            name="select_open_reviews",
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name="issue",
            name="doi",
            field=models.CharField(
                blank=True,
                help_text="The DOI (not URL) to be registered for the issue when registering articles that are part of this issue. If you have enabled issue autoregistration in your settings, this field should not be entered manually.",
                max_length=255,
                null=True,
                verbose_name="DOI",
            ),
        ),
    ]
