# -*- coding: utf-8 -*-
'''
Created on Jan 29, 2012

@author: ymh
'''
from django.core.management.base import NoArgsCommand
from django.core.management.color import no_style
import urllib
from hdabo.utils import show_progress
import re
from hdalab.models import CountryCode

class Command(NoArgsCommand):
    def handle_noargs(self, **options):
        self.style = no_style()
        
        
        f = urllib.urlopen("http://fr.wikipedia.org/wiki/ISO_3166-1?action=raw&section=3")
        lines = f.read().split("|-")
        
        total = len(lines)
        writer = None
        
        for i,line in enumerate(lines):
            writer = show_progress(i+1, total, line.decode("utf-8"), 50, writer)
            isocode = re.findall("(?m)(\[\[|\|)([A-Z]{3})]]", line)
            countryname = re.findall("(?m)\{\{([^|}]+)", line)
            if len(isocode) and len(countryname):
                isocode = isocode[0][1]
                countryname = countryname[0].strip()
                CountryCode.objects.get_or_create(label=countryname, isocode=isocode)
