# -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-03-06 10:14
from __future__ import unicode_literals

from django.db import migrations


OLD_ROLE_NAME = 'partner_coordinator'
NEW_ROLE_NAME = 'project_coordinator'
USER_ROLE_MODELS = [
    'CourseUserRole', 'OrganizationUserRole', 'HistoricalCourseUserRole', 'HistoricalOrganizationUserRole'
]
STATE_MODELS = ['CourseState', 'CourseRunState', 'HistoricalCourseState', 'HistoricalCourseRunState']


def get_publisher_model(apps, model_name):
    return apps.get_model('publisher', model_name)


def update_value(model, field_name, reverse):
    filter_value = OLD_ROLE_NAME
    updated_value = NEW_ROLE_NAME
    if reverse:
        filter_value = NEW_ROLE_NAME
        updated_value = OLD_ROLE_NAME

    model.objects.filter(**{field_name: filter_value}).update(**{field_name: updated_value})


def update_user_role_models(apps, reverse=False):
    for model_name in USER_ROLE_MODELS:
        update_value(get_publisher_model(apps, model_name), 'role', reverse)


def update_state_models(apps, reverse=False):
    for model_name in STATE_MODELS:
        model = get_publisher_model(apps, model_name)
        update_value(model, 'approved_by_role', reverse)
        update_value(model, 'owner_role', reverse)


def forwards_data(apps, schema_editor):
    """
    Change choice value from 'partner_coordinator' to 'project_coordinator'
    """
    update_user_role_models(apps)
    update_state_models(apps)


def reverse_data(apps, schema_editor):
    """
    Change choice value from 'project_coordinator' to 'partner_coordinator'
    """
    update_user_role_models(apps, reverse=True)
    update_state_models(apps, reverse=True)


class Migration(migrations.Migration):

    dependencies = [
        ('publisher', '0041_auto_20170306_1002'),
    ]

    operations = [
        migrations.RunPython(forwards_data, reverse_data),
    ]
