import urllib
import bz2
import json
import logging

from django.utils import timezone
from django.core.management.base import BaseCommand
from ...models import StreetModel, BaseAdresse
from django.utils.translation import ugettext_lazy as _


class Command(BaseCommand):
    help = _('Retrieve streets update saved and apply them. No args needed.')

    def launch_update(self, zipcode, start_update):
        file_zip = urllib.urlretrieve('http://bano.openstreetmap.fr/BAN_odbl/BAN_odbl_{}-json.bz2'.format(zipcode[:2]))
        file_unzip = bz2.BZ2File(file_zip[0])

        zip_lines = file_unzip.readlines()

        for line in zip_lines:
            street_info = json.loads(line)
            if street_info['type'] == 'street' and street_info['postcode'].startswith(zipcode):
                street = StreetModel.objects.get_or_create(citycode=street_info['citycode'],
                                                           name=street_info['name'])
                street[0].city = street_info['city']
                street[0].name = street_info['name'][:149]
                street[0].zipcode = street_info['postcode']
                street[0].type = street_info['type']
                street[0].citycode = street_info['citycode']
                street[0].save()

        StreetModel.objects.filter(last_update__lt=start_update, zipcode__startswith=zipcode).delete()

    def handle(self, *args, **options):
        logging.basicConfig()
        logger = logging.getLogger(__name__)
        for base_adr in BaseAdresse.objects.exclude(zipcode=''):
            try:
                self.launch_update(base_adr.zipcode, timezone.now())
            except Exception as e:
                logger.exception(u'error while updating base_adresse %s: %s', base_adr.title, e)
