# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-24 19:33
from __future__ import unicode_literals

import os
import json
import logging

from django.db import migrations

from website import settings
from osf.models import NodeLicense

logger = logging.getLogger(__file__)


def add_licenses(*args):
    """Upsert the licenses in our database based on a JSON file.

    :return tuple: (number inserted, number updated)

    Moved from website/project/licenses/__init__.py
    """
    ninserted = 0
    nupdated = 0
    with open(
            os.path.join(
                settings.APP_PATH,
                'node_modules', 'list-of-licenses', 'dist', 'list-of-licenses.json'
            )
    ) as fp:
        licenses = json.loads(fp.read())
        for id, info in licenses.items():
            name = info['name']
            text = info['text']
            properties = info.get('properties', [])

            model_kwargs = dict(
                license_id=id,
                name=name,
                text=text,
                properties=properties
            )

            node_license, created = NodeLicense.objects.get_or_create(**model_kwargs)

            if not created:
                node_license.name = name
                node_license.text = text
                node_license.properties = properties
                node_license.save()
                nupdated += 1
            else:
                ninserted += 1

            logger.info('License {name} ({id}) added to the database.'.format(name=name, id=id))

    logger.info('{} licenses inserted into the database, {} licenses updated in the database.'.format(
        ninserted, nupdated
    ))


def remove_licenses(*args):
    ndeleted = 0
    with open(
            os.path.join(
                settings.APP_PATH,
                'node_modules', 'list-of-licenses', 'dist', 'list-of-licenses.json'
            )
    ) as fp:
        licenses = json.loads(fp.read())
        for id, info in licenses.items():
            name = info['name']
            text = info['text']
            properties = info.get('properties', [])

            model_kwargs = dict(
                license_id=id,
                name=name,
                text=text,
                properties=properties
            )

            try:
                node_license = NodeLicense.objects.get(**model_kwargs)
                node_license.delete()
                ndeleted += 1
                logger.info('License {name} ({id}) removed from the database.'.format(name=name, id=id))
            except NodeLicense.DoesNotExist:
                pass

    logger.info('{} licenses removed from the database.'.format(ndeleted))


class Migration(migrations.Migration):

    dependencies = [
        ('osf', '0034_rename_email_user_relation'),
    ]

    operations = [
        migrations.RunPython(add_licenses, remove_licenses),
    ]

Add migration for ensure_licenses