import re
from calibre.web.feeds.news import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import Comment

class GazetaWspolczesna(BasicNewsRecipe):
    title          = u'Gazeta Wsp\xf3\u0142czesna'
    __author__        = 'fenuks'
    description   = u'Gazeta Współczesna - portal regionalny.'
    category       = 'newspaper'
    language       = 'pl'
    encoding = 'iso-8859-2'
    extra_css = 'ul {list-style: none; padding:0; margin:0;}'
    INDEX = 'http://www.wspolczesna.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'}

    preprocess_regexps = [(re.compile(ur'Czytaj:.*?</a>', re.DOTALL), lambda match: ''), (re.compile(ur'Przeczytaj także:.*?</a>', re.DOTALL|re.IGNORECASE), lambda match: ''), 
                          (re.compile(ur'Przeczytaj również:.*?</a>', re.DOTALL|re.IGNORECASE), lambda match: ''), (re.compile(ur'Zobacz też:.*?</a>', re.DOTALL|re.IGNORECASE), lambda match: '')]
    
    keep_only_tags = [dict(id=['article', 'cover', 'photostory'])]
    remove_tags = [dict(id=['articleTags', 'articleMeta', 'boxReadIt', 'articleGalleries', 'articleConnections',
                  'ForumArticleComments', 'articleRecommend', 'jedynkiLinks', 'articleGalleryConnections', 
                  'photostoryConnections', 'articleEpaper', 'articlePoll', 'articleAlarm', 'articleByline']), 
                  dict(attrs={'class':'articleFunctions'})]

    feeds          = [(u'Wszystkie', u'http://www.wspolczesna.pl/rss.xml'), (u'August\xf3w', u'http://www.wspolczesna.pl/augustow.xml'), (u'Bia\u0142ystok', u'http://www.wspolczesna.pl/bialystok.xml'), (u'Bielsk Podlaski', u'http://www.wspolczesna.pl/bielsk.xml'), (u'E\u0142k', u'http://www.wspolczesna.pl/elk.xml'), (u'Grajewo', u'http://www.wspolczesna.pl/grajewo.xml'), (u'Go\u0142dap', u'http://www.wspolczesna.pl/goldap.xml'), (u'Hajn\xf3wka', u'http://www.wspolczesna.pl/hajnowka.xml'), (u'Kolno', u'http://www.wspolczesna.pl/kolno.xml'), (u'\u0141om\u017ca', u'http://www.wspolczesna.pl/lomza.xml'), (u'Mo\u0144ki', u'http://www.wspolczesna.pl/monki.xml'), (u'Olecko', u'http://www.wspolczesna.pl/olecko.xml'), (u'Ostro\u0142\u0119ka', u'http://www.wspolczesna.pl/ostroleka.xml'), (u'Powiat Bia\u0142ostocki', u'http://www.wspolczesna.pl/powiat.xml'), (u'Sejny', u'http://www.wspolczesna.pl/sejny.xml'), (u'Siemiatycze', u'http://www.wspolczesna.pl/siemiatycze.xml'), (u'Sok\xf3\u0142ka', u'http://www.wspolczesna.pl/sokolka.xml'), (u'Suwa\u0142ki', u'http://www.wspolczesna.pl/suwalki.xml'), (u'Wysokie Mazowieckie', u'http://www.wspolczesna.pl/wysokie.xml'), (u'Zambr\xf3w', u'http://www.wspolczesna.pl/zambrow.xml'), (u'Sport', u'http://www.wspolczesna.pl/sport.xml'), (u'Praca', u'http://www.wspolczesna.pl/praca.xml'), (u'Dom', u'http://www.wspolczesna.pl/dom.xml'), (u'Auto', u'http://www.wspolczesna.pl/auto.xml'), (u'Zdrowie', u'http://www.wspolczesna.pl/zdrowie.xml')]

    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 append_page(self, soup, appendtag):
        tag = soup.find('span', attrs={'class':'photoNavigationPages'})
        if tag:
            number = int(tag.string.rpartition('/')[-1].replace('&nbsp;', ''))
            baseurl = self.INDEX + soup.find(attrs={'class':'photoNavigationNext'})['href'][:-1]

            for r in appendtag.findAll(attrs={'class':'photoNavigation'}):
                r.extract()
            for nr in range(2, number+1):
                soup2 = self.index_to_soup(baseurl + str(nr))
                pagetext = soup2.find(id='photoContainer')
                if pagetext:
                    pos = len(appendtag.contents)
                    appendtag.insert(pos, pagetext)
                pagetext = soup2.find(attrs={'class':'photoMeta'})
                if pagetext:
                    pos = len(appendtag.contents)
                    appendtag.insert(pos, pagetext)
                pagetext = soup2.find(attrs={'class':'photoStoryText'})
                if pagetext:
                    pos = len(appendtag.contents)
                    appendtag.insert(pos, pagetext)
            
            comments = appendtag.findAll(text=lambda text:isinstance(text, Comment))
            for comment in comments:
                comment.extract()

    def preprocess_html(self, soup):
        self.append_page(soup, soup.body)
        return soup
