# Path: montanha/models.py
# class Legislator(models.Model):
# 
#     class Meta:
#         verbose_name = _("Legislator")
#         verbose_name_plural = _("Legislators")
# 
#     name = models.CharField(max_length=2048,
#                             verbose_name=_("Full name"))
# 
#     alternative_names = models.ManyToManyField('AlternativeLegislatorName')
# 
#     picture = ThumbnailerImageField(
#         verbose_name=_('Picture'),
#         upload_to='legislator',
#         max_length=256,
#         blank=True,
#         null=True)
# 
#     site = models.URLField(
#         verbose_name=_('Site'),
#         blank=True,
#         null=True)
# 
#     email = models.EmailField(
#         verbose_name=_('Email'),
#         blank=True,
#         null=True)
# 
#     about = models.TextField(
#         verbose_name=_('About'),
#         blank=True,
#         null=True)
# 
#     gender = models.CharField(
#         verbose_name=_('Gender'),
#         choices=(
#             ('F', _('Female')),
#             ('M', _('Male'))),
#         blank=True,
#         null=True,
#         max_length=1)
# 
#     date_of_birth = models.DateField(
#         verbose_name=_('Date of Birth'),
#         blank=True,
#         null=True)
# 
#     def __unicode__(self):
#         return u"Legislator %s" % (self.name)
# 
#     @property
#     def party(self):
#         party = self.mandate_set.order_by("-date_start")[0].party
#         if party and party.siglum:
#             return party.siglum
#         return u"Partido não informado"


import os
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
from django.core.files import File
from montanha.models import Legislator




SITE_URL = "http://www.almg.gov.br"
PAGE_URL = "%s/%s" % (
    SITE_URL, (
        "/deputados/conheca_deputados/index.html?aba=js_tabAtual"
        "&rdSituacaoAnt=Exercicio&sltResult=0&formato=imagem"
        "&sltLegAnt=16&rdSituacao=Exercicio"
    )
)
req = urllib2.Request(PAGE_URL, headers={"User-Agent": "Mozilla/5.0"})
html = urllib2.urlopen(req)
doc = BeautifulSoup(html)

ul = doc.find("ul", {"id": "deputados_view-imagem"})
for item in ul.findAll("li"):
    try:
        # FIXME
        picture_url = "%s%s" % (SITE_URL, item.find("img")["src"])
        picture_url = picture_url.rsplit("?__scale=w:109,h:120,t:4")[0]

        legislator_name = item.find("p", {"class": "titulo"}).find("a").string
        leg = Legislator.objects.get(name=str(legislator_name))

        result = urllib.urlretrieve(picture_url)
        leg.picture.save(os.path.basename(picture_url), File(open(result[0])))
        leg.save()
        print "{0} => {1}".format(legislator_name, picture_url)

# Path: montanha/models.py
# class Legislator(models.Model):
# 
#     class Meta:
#         verbose_name = _("Legislator")
#         verbose_name_plural = _("Legislators")
# 
#     name = models.CharField(max_length=2048,
#                             verbose_name=_("Full name"))
# 
#     alternative_names = models.ManyToManyField('AlternativeLegislatorName')
# 
#     picture = ThumbnailerImageField(
#         verbose_name=_('Picture'),
#         upload_to='legislator',
#         max_length=256,
#         blank=True,
#         null=True)
# 
#     site = models.URLField(
#         verbose_name=_('Site'),
#         blank=True,
#         null=True)
# 
#     email = models.EmailField(
#         verbose_name=_('Email'),
#         blank=True,
#         null=True)
# 
#     about = models.TextField(
#         verbose_name=_('About'),
#         blank=True,
#         null=True)
# 
#     gender = models.CharField(
#         verbose_name=_('Gender'),
#         choices=(
#             ('F', _('Female')),
#             ('M', _('Male'))),
#         blank=True,
#         null=True,
#         max_length=1)
# 
#     date_of_birth = models.DateField(
#         verbose_name=_('Date of Birth'),
#         blank=True,
#         null=True)
# 
#     def __unicode__(self):
#         return u"Legislator %s" % (self.name)
# 
#     @property
#     def party(self):
#         party = self.mandate_set.order_by("-date_start")[0].party
#         if party and party.siglum:
#             return party.siglum
#         return u"Partido não informado"


# Path: scripts/get_legislator_picture.py
import os
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
from django.core.files import File
from montanha.models import Legislator





SITE_URL = "http://www.almg.gov.br"
PAGE_URL = "%s/%s" % (
    SITE_URL, (
        "/deputados/conheca_deputados/index.html?aba=js_tabAtual"
        "&rdSituacaoAnt=Exercicio&sltResult=0&formato=imagem"
        "&sltLegAnt=16&rdSituacao=Exercicio"
    )
)
req = urllib2.Request(PAGE_URL, headers={"User-Agent": "Mozilla/5.0"})
html = urllib2.urlopen(req)
doc = BeautifulSoup(html)

ul = doc.find("ul", {"id": "deputados_view-imagem"})
for item in ul.findAll("li"):
    try:
        # FIXME
        picture_url = "%s%s" % (SITE_URL, item.find("img")["src"])
        picture_url = picture_url.rsplit("?__scale=w:109,h:120,t:4")[0]

        legislator_name = item.find("p", {"class": "titulo"}).find("a").string
        leg = Legislator.objects.get(name=str(legislator_name))

        result = urllib.urlretrieve(picture_url)
        leg.picture.save(os.path.basename(picture_url), File(open(result[0])))
        leg.save()
        print "{0} => {1}".format(legislator_name, picture_url)

    except Legislator.DoesNotExist: