#!/usr/bin/env python
__author__ = 'Jordi Balcells'
__license__ = 'GPL v3'
description = 'Jornal portugu\xeas - v1.03 (16 June 2010)'
__docformat__ = 'restructuredtext en'

'''
publico.pt
'''

from calibre.web.feeds.news import BasicNewsRecipe
from polyglot.urllib import urlencode


def classes(classes):
    q = frozenset(classes.split(' '))
    return dict(attrs={'class': lambda x: x and frozenset(x.split()).intersection(q)})


class PublicoPT(BasicNewsRecipe):
    description = 'Jornal portugu\xeas'
    cover_url = 'http://static.publico.pt/files/header/img/publico.gif'
    title = 'Publico.PT'
    category = 'News, politics, culture, economy, general interest'
    oldest_article = 2
    no_stylesheets = True
    encoding = 'utf8'
    use_embedded_content = False
    language = 'pt'
    remove_empty_feeds = True
    extra_css = ' body{font-family: Arial,Helvetica,sans-serif } img{margin-bottom: 0.4em} '
    needs_subscription = True

    keep_only_tags = [
        dict(id='story-content story-header'.split()),
    ]
    remove_tags = [
        classes('social-tools'),
    ]
    remove_attributes = ['style']

    feeds = [
        ('Geral', 'http://feeds.feedburner.com/publicoRSS'),
        ('Mundo', 'http://feeds.feedburner.com/PublicoMundo'),
        ('Pol\xedtica', 'http://feeds.feedburner.com/PublicoPolitica'),
        ('Economia', 'http://feeds.feedburner.com/PublicoEconomia'),
        ('Desporto', 'http://feeds.feedburner.com/PublicoDesporto'),
        ('Sociedade', 'http://feeds.feedburner.com/PublicoSociedade'),
        ('Educa\xe7\xe3o', 'http://feeds.feedburner.com/PublicoEducacao'),
        ('Ci\xeancias', 'http://feeds.feedburner.com/PublicoCiencias'),
        ('Ecosfera', 'http://feeds.feedburner.com/PublicoEcosfera'),
        ('Cultura', 'http://feeds.feedburner.com/PublicoCultura'),
        ('Local', 'http://feeds.feedburner.com/PublicoLocal'),
        ('Tecnologia', 'http://feeds.feedburner.com/PublicoTecnologia'),
    ]

    def get_browser(self):
        br = BasicNewsRecipe.get_browser(self)
        if self.username is not None and self.password is not None:
            postdata = urlencode({'username': self.username, 'password': self.password})
            br.open('https://www.publico.pt/api/user/login', data=postdata, timeout=self.timeout)

            br.set_handle_refresh(True)

        return br

    def preprocess_html(self, soup):
        for img in soup.findAll('img', attrs={'data-media-viewer': True}):
            img['src'] = img['data-media-viewer']
        return soup
