from calibre.web.feeds.news import BasicNewsRecipe


class GCN(BasicNewsRecipe):
    title = u'Gazeta Codziennej Nowiny'
    __author__ = 'fenuks'
    description = u'nowiny24.pl - portal regionalny województwa podkarpackiego.'
    category = 'newspaper'
    language = 'pl'
    encoding = 'iso-8859-2'
    extra_css = 'ul {list-style: none; padding:0; margin:0;}'
    INDEX = 'http://www.nowiny24.pl'
    masthead_url = INDEX + '/images/top_logo.png'
    oldest_article = 7
    max_articles_per_feed = 100
    remove_empty_feeds = True
    no_stylesheets = True
    ignore_duplicate_articles = {'title', 'url'}
    remove_attributes = ['style']
    use_embedded_content = False

    feeds = [(u'Wszystkie', u'http://www.nowiny24.pl/rss.xml'),
             (u'Podkarpacie', u'http://www.nowiny24.pl/podkarpacie.xml'),
             (u'Bieszczady', u'http://www.nowiny24.pl/bieszczady.xml'),
             (u'Rzeszów', u'http://www.nowiny24.pl/rzeszow.xml'),
             (u'Przemyśl', u'http://www.nowiny24.pl/przemysl.xml'),
             (u'Leżajsk', u'http://www.nowiny24.pl/lezajsk.xml'),
             (u'Łańcut', u'http://www.nowiny24.pl/lancut.xml'),
             (u'Dębica', u'http://www.nowiny24.pl/debica.xml'),
             (u'Jarosław', u'http://www.nowiny24.pl/jaroslaw.xml'),
             (u'Krosno', u'http://www.nowiny24.pl/krosno.xml'),
             (u'Mielec', u'http://www.nowiny24.pl/mielec.xml'),
             (u'Nisko', u'http://www.nowiny24.pl/nisko.xml'),
             (u'Sanok', u'http://www.nowiny24.pl/sanok.xml'),
             (u'Stalowa Wola', u'http://www.nowiny24.pl/stalowawola.xml'),
             (u'Tarnobrzeg', u'http://www.nowiny24.pl/tarnobrzeg.xml'),
             (u'Sport', u'http://www.nowiny24.pl/sport.xml'),
             (u'Dom', u'http://www.nowiny24.pl/dom.xml'),
             (u'Auto', u'http://www.nowiny24.pl/auto.xml'),
             (u'Praca', u'http://www.nowiny24.pl/praca.xml'),
             (u'Zdrowie', u'http://www.nowiny24.pl/zdrowie.xml'),
             (u'Wywiady', u'http://www.nowiny24.pl/wywiady.xml')]

    keep_only_tags = [dict(id='article')]

    def get_cover_url(self):
        soup = self.index_to_soup(
            self.INDEX + '/apps/pbcs.dll/section?Category=JEDYNKI')
        nexturl = self.INDEX + soup.find(id='covers').find('a')['href']
        soup = self.index_to_soup(nexturl)
        self.cover_url = self.INDEX + \
            soup.find(id='cover').find(name='img')['src']
        return getattr(self, 'cover_url', self.cover_url)

    def decode_feedportal_url(self, url):
        link = url.rpartition('l/0L0S')[2][:-12]
        replaces = (('0B', '.'), ('0C', '/'), ('0H', ','),
                    ('0D', '?'), ('0F', '='), ('0A', '0'), ('0I', '_'))
        for t in replaces:
            link = link.replace(*t)
        return 'http://' + link

    def print_version(self, url):
        return self.decode_feedportal_url(url) + '&Template=printpicart'
