from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.translation import ugettext as _

from candidates.models.popit import create_or_update
from candidates.popit import PopItApiMixin
from candidates.election_specific import MAPIT_DATA, AREA_POST_DATA

from slumber.exceptions import HttpServerError, HttpClientError

class Command(PopItApiMixin, BaseCommand):
    help = "Create or update the required posts in PopIt"

    def handle_mapit_type(self, election, election_data, mapit_type):
        mapit_tuple = (mapit_type, election_data['mapit_generation'])
        for id, area in MAPIT_DATA.areas_by_id[mapit_tuple].items():
            post_id = AREA_POST_DATA.get_post_id(
                election, mapit_type, id
            )
            role = election_data['for_post_role']
            area_mapit_url = settings.MAPIT_BASE_URL + 'area/' + str(area['id'])
            post_data = {
                'role': role,
                'id': post_id,
                'label': _('{post_role} for {area_name}').format(
                    post_role=role, area_name=area['name']
                ),
                'area': {
                    'name': area['name'],
                    'id': 'mapit:' + str(area['id']),
                    'identifier': area_mapit_url,
                },
                'organization_id': election_data['organization_id'],
            }
            create_or_update(self.api.posts, post_data)

    def handle(self, **options):
        try:
            for election, election_data in settings.ELECTIONS.items():
                for mapit_type in election_data['mapit_types']:
                    self.handle_mapit_type(election, election_data, mapit_type)
        except (HttpServerError, HttpClientError) as hse:
            print "The body of the error was:", hse.content
            raise

@@ -1,20 +1,54 @@
+from optparse import make_option%0A%0A
 from django.core.man
@@ -79,16 +79,16 @@
 Command%0A
-
 from dja
@@ -504,73 +504,502 @@
     
-def handle_mapit_type(self, election, election_data, mapit_type):
+option_list = BaseCommand.option_list + (%0A        make_option(%0A            '--post-label',%0A            help='Override the format string used to construct the post label %5Bdefault: %22%25default%22%5D',%0A            default=_('%7Bpost_role%7D for %7Barea_name%7D'),%0A        ),%0A    )%0A%0A    def handle_mapit_type(self, election, election_data, mapit_type, **options):%0A        post_label_format = _('%7Bpost_role%7D for %7Barea_name%7D')%0A        if options%5B'post_label'%5D:%0A            post_label_format = options%5B'post_label'%5D
 %0A   
@@ -1486,40 +1486,25 @@
 l': 
-_('%7B
 post_
-role%7D for %7Barea_name%7D')
+label_format
 .for
@@ -2141,16 +2141,41 @@
 it_type(
+%0A                        
 election
@@ -2201,16 +2201,48 @@
 pit_type
+, **options%0A                    
 )%0A      

Make it possible to override the post label form string