# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-27 17:19
from __future__ import unicode_literals
import logging

from django.db import migrations
from osf.models import PreprintService
logger = logging.getLogger(__name__)

def add_preprint_doi_created(apps, schema_editor):
    """
    Data migration that makes preprint_doi_created equal to date_published for existing published preprints.
    """
    null_preprint_doi_created = PreprintService.objects.filter(preprint_doi_created__isnull=True, date_published__isnull=False)
    preprints_count = null_preprint_doi_created.count()
    current_preprint = 0
    logger.info('{} published preprints found with preprint_doi_created is null.'.format(preprints_count))

    for preprint in null_preprint_doi_created:
        current_preprint += 1
        if preprint.get_identifier('doi'):
            preprint.preprint_doi_created = preprint.date_published
            preprint.save()
            logger.info('Preprint ID {}, {}/{} preprint_doi_created field populated.'.format(preprint._id, current_preprint, preprints_count))
        else:
            logger.info('Preprint ID {}, {}/{} skipped because a DOI has not been created.'.format(preprint._id, current_preprint, preprints_count))

def reverse_func(apps, schema_editor):
    """
    Reverses data migration. Sets preprint_doi_created field back to null.
    """
    preprint_doi_created_not_null = PreprintService.objects.filter(preprint_doi_created__isnull=False)
    preprints_count = preprint_doi_created_not_null.count()
    current_preprint = 0
    logger.info('Reversing preprint_doi_created migration.')

    for preprint in preprint_doi_created_not_null:
        current_preprint += 1
        preprint.preprint_doi_created = None
        preprint.save()
        logger.info('Preprint ID {}, {}/{} preprint_doi_created field set to None.'.format(preprint._id, current_preprint, preprints_count))

class Migration(migrations.Migration):

    dependencies = [
        ('osf', '0068_preprintservice_preprint_doi_created'),
    ]

    operations = [
         migrations.RunPython(add_preprint_doi_created, reverse_func)
    ]

Add data migration to populate preprint_doi_created field on existing published preprints where DOI identifier exists. Set to preprint date_published field.
Add data migration to populate preprint_doi_created field on existing published preprints where DOI identifier exists.  Set to preprint date_published field.
