# -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-04-28 08:11
from __future__ import unicode_literals
import os

from django.core.files.base import ContentFile
from django.db import migrations
from django.conf import settings

OLD_LABEL = "Janeway default"
NEW_LABEL = "Janeway default (1.3.7)"
COMMENTS = """
Changes from v1.3.7:
    - mixed-citation objects rendered as they are
    - Fixes sec tag ids being rendered (e.g "sec1")
    - Renders headings within the reference block
    - Avoids duplicate "References" headings
"""


def upgrade(apps, schema_editor):
    """Installs the latest default XSLT preserving the previous one

    Only runs if the previous version XSLT was installed.
    If it was, it relabels it (the old label had no version), installs
    the new one and swaps any journals using the old default to use the
    new.
    """
    XSLFile = apps.get_model("core", "XSLFile")
    Journal = apps.get_model("journal", "Journal")
    try:
        old_default = XSLFile.objects.get(label=OLD_LABEL)
    except XSLFile.DoesNotExist:
        return
    else:
        xsl_path = os.path.join(settings.BASE_DIR, "transform/xsl/default.xsl")
        with open(xsl_path, "rb") as f:
            xsl_file = ContentFile(f.read())
            xsl_file.name = "default.xsl"

            new_default, c = XSLFile.objects.get_or_create(
                label=settings.DEFAULT_XSL_FILE_LABEL,
                defaults={
                    "comments": COMMENTS,
                    "file": xsl_file,
                },
            )
        old_default.label = NEW_LABEL
        old_default.save()
        journals = Journal.objects.all()
        for journal in journals:
            if journal.xsl == old_default:
                journal.xsl = new_default
                journal.save()


class Migration(migrations.Migration):
    dependencies = [
        ("core", "0037_journal_xsl_files"),
    ]

    operations = [migrations.RunPython(upgrade, reverse_code=migrations.RunPython.noop)]
