# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import re

from django.db import migrations


def adjust_roles_for_grouping(apps, schema_editor):
    Election = apps.get_model('elections', 'Election')
    for election in Election.objects.all():
        if re.search(r'^local\.[^.]+\.2016', election.slug):
            election.for_post_role = 'Local Councillor'
            election.save()
        if re.search(r'^mayor\.[^.]+\.2016', election.slug):
            election.for_post_role = 'Mayor'
            election.save()


class Migration(migrations.Migration):

    dependencies = [
        ('uk', '0002_remove-gb-prefix'),
    ]

    operations = [
        migrations.RunPython(adjust_roles_for_grouping),
    ]

Change for_post_role of local & mayoral elections for better grouping
Change for_post_role of local & mayoral elections for better grouping

On various pages we're now grouping elections by the post role that
they're for.  Unfortunately in some UK installations there's a different
for_post_role for each local councillor election, and each mayoral
election (e.g. 'Councillor for St Helens' rather than 'Local
councillor')

This data migration looks for elections with slugs that match the local
and mayoral elections in 2016 according to:

  https://democracyclub.org.uk/projects/election-ids/reference/

... and sets for_post_role on each of them to 'Local Councillor' and
'Mayor' respectively.
