import re

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


class in4(BasicNewsRecipe):
    title = 'IN4.pl'
    oldest_article = 7
    max_articles_per_feed = 100
    __author__ = 'fenuks'
    description = 'Serwis Informacyjny - Aktualnosci, recenzje'
    category = 'IT'
    language = 'pl'
    index = 'http://www.in4.pl/'
    no_stylesheets = True
    remove_empty_feeds = True
    preprocess_regexps = [(re.compile(r'<a title="translate into.*?</a>', re.DOTALL), lambda match: '')]
    keep_only_tags = [dict(name='div', attrs={'class': 'left_alone'})]
    remove_tags_after = dict(name='img', attrs={'title': 'komentarze'})
    remove_tags = [dict(name='img', attrs={'title': 'komentarze'})]
    feeds = [
        ('Wiadomo\u015bci', 'http://www.in4.pl/rss.php'),
        ('Recenzje', 'http://www.in4.pl/rss_recenzje.php'),
        ('Mini recenzje', 'http://www.in4.pl/rss_mini.php'),
    ]

    def append_page(self, soup, appendtag):
        a = soup.findAll('a')
        nexturl = None
        for i in a:
            if i.string and 'następna str' in i.string:
                nexturl = 'http://www.in4.pl/' + i['href']
                i.extract()
        while nexturl:
            soup2 = self.index_to_soup(nexturl)
            pagetext = soup2.find(id='news')
            comments = pagetext.findAll(text=lambda text: isinstance(text, Comment))
            for comment in comments:
                comment.extract()
            pos = len(appendtag.contents)
            appendtag.insert(pos, pagetext)
            nexturl = None
            tag = soup2.findAll('a')
            for z in tag:
                if z.string and 'następna str' in z.string:
                    nexturl = 'http://www.in4.pl/' + z['href']
                    break

    def preprocess_html(self, soup):
        self.append_page(soup, soup.body)
        for a in soup.findAll('a', href=True):
            if 'http://' not in a['href'] and 'https://' not in a['href']:
                a['href'] = self.index + a['href']
        return soup
