# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-08-31 18:13
from __future__ import unicode_literals

from django.db import migrations
from django.http import Http404

import json
import logging

from ccx_keys.locator import CCXLocator
from courseware.courses import get_course_by_id
from xmodule.modulestore.django import SignalHandler

log = logging.getLogger(__name__)


def save_display_name(apps, schema_editor):
    '''
    Add override for `display_name` for CCX courses that don't have one yet.
    '''
    CcxFieldOverride = apps.get_model('ccx', 'CcxFieldOverride')
    CustomCourseForEdX = apps.get_model('ccx', 'CustomCourseForEdX')

    # Build list of CCX courses that don't have an override for `display_name` yet
    ccx_display_name_present_ids = list(CcxFieldOverride.objects.filter(
        field='display_name').values_list('ccx__id', flat=True))
    ccx_list = CustomCourseForEdX.objects.exclude(id__in=ccx_display_name_present_ids)

    # Create `display_name` overrides for these CCX courses
    for ccx in ccx_list:
        try:
            course = get_course_by_id(ccx.course_id, depth=None)
        except Http404:
            log.error('Root course %s not found. Skipping saving course display name', ccx.course_id)
            continue
        display_name = course.fields['display_name']
        display_name_json = display_name.to_json(ccx.display_name)
        serialized_display_name = json.dumps(display_name_json)

        CcxFieldOverride.objects.get_or_create(
            ccx=ccx,
            location=course.location,
            field='display_name',
            defaults={'value': serialized_display_name},
        )

        # Publish change
        responses = SignalHandler.course_published.send(
            sender=ccx,
            course_key=CCXLocator.from_course_locator(course.id, unicode(ccx.id))
        )
        for rec, response in responses:
            log.info(
                'Signal fired when course is published. Course %s. Receiver: %s. Response: %s',
                ccx.course_id,
                rec,
                response
            )


class Migration(migrations.Migration):

    dependencies = [
        ('ccx', '0005_change_ccx_coach_to_staff'),
    ]

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

@@ -1170,17 +1170,34 @@
 g.error(
-'
+%0A                %22
 Root cou
@@ -1218,29 +1218,19 @@
 nd. 
-Skipping saving cours
+Can't creat
 e di
@@ -1238,29 +1238,109 @@
 play
- 
+_
 name
-', ccx.course_id
+ override for %25s.%22,%0A                ccx.course_id,%0A                ccx.display_name%0A            
 )%0A  

Update log message.