# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-07-31 04:52
from __future__ import unicode_literals

import re

from django.db import migrations


def update_event_types_names(apps, schema_editor):
    Action = apps.get_model('actstream', 'Action')
    StoredEventType = apps.get_model('events', 'StoredEventType')

    known_namespaces = {
        'documents_': 'documents.',
        'checkouts_': 'checkouts.',
        'document_comment_': 'document_comments.',
        'parsing_document_': 'document_parsing.',
        'ocr_': 'ocr.',
        'tag_': 'tags.',
    }

    pattern = re.compile('|'.join(known_namespaces.keys()))

    for event_type in StoredEventType.objects.all():
        event_type.name = pattern.sub(
            lambda x: known_namespaces[x.group()], event_type.name
        )
        event_type.save()

    for action in Action.objects.all():
        action.verb = pattern.sub(
            lambda x: known_namespaces[x.group()], action.verb
        )
        action.save()


def revert_event_types_names(apps, schema_editor):
    Action = apps.get_model('actstream', 'Action')
    StoredEventType = apps.get_model('events', 'StoredEventType')

    known_namespaces = {
        'documents\.': 'documents_',
        'checkouts\.': 'checkouts_',
        'document_comments\.': 'document_comment_',
        'document_parsing\.': 'parsing_document_',
        'ocr\.': 'ocr_',
        'tags\.': 'tag_',
    }

    pattern = re.compile('|'.join(known_namespaces.keys()))

    for event_type in StoredEventType.objects.all():
        old_name = event_type.name
        new_name = pattern.sub(
            lambda x: known_namespaces[x.group().replace('.', '\\.')],
            event_type.name
        )
        event_type.name = new_name
        if old_name == new_name:
            event_type.delete()
        else:
            event_type.save()

    for action in Action.objects.all():
        new_name = pattern.sub(
            lambda x: known_namespaces[x.group().replace('.', '\\.')],
            action.verb
        )
        action.verb = new_name
        action.save()


class Migration(migrations.Migration):

    dependencies = [
        ('events', '0004_auto_20170731_0423'),
        ('actstream', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(
            code=update_event_types_names,
            reverse_code=revert_event_types_names
        ),
    ]
