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


class LinuxJournal(BasicNewsRecipe):
    title = u'Linux Journal'
    __author__ = 'fenuks'
    description = u'The monthly magazine of the Linux community, promoting the use of Linux worldwide.'
    cover_url = 'http://www.linuxjournal.com/files/linuxjournal.com/ufiles/logo-lj.jpg'
    category = 'IT, Linux'
    language = 'en'
    oldest_article = 7
    max_articles_per_feed = 100
    no_stylesheets = True
    use_embedded_content = False
    remove_empty_feeds = True
    keep_only_tags = [dict(id='content-inner')]
    remove_tags_after = dict(attrs={'class': 'user-signature clear-block'})
    remove_tags = [dict(attrs={
                        'class': ['user-signature clear-block', 'breadcrumb',  'terms terms-inline']})]
    feeds = [
    (u'Front Page', u'http://feeds.feedburner.com/linuxjournalcom'),
    (u'News', u'http://feeds.feedburner.com/LinuxJournal-BreakingNews'),
    (u'Blogs', u'http://www.linuxjournal.com/blog/feed'),
    (u'Audio/Video', u'http://www.linuxjournal.com/taxonomy/term/28/0/feed'),
    (u'Community', u'http://www.linuxjournal.com/taxonomy/term/18/0/feed'),
    (u'Education', u'http://www.linuxjournal.com/taxonomy/term/25/0/feed'),
    (u'Embedded', u'http://www.linuxjournal.com/taxonomy/term/27/0/feed'),
    (u'Hardware', u'http://www.linuxjournal.com/taxonomy/term/23/0/feed'),
    (u'HOWTOs', u'http://www.linuxjournal.com/taxonomy/term/19/0/feed'),
    (u'International', u'http://www.linuxjournal.com/taxonomy/term/30/0/feed'),
    (u'Security', u'http://www.linuxjournal.com/taxonomy/term/31/0/feed'),
    (u'Software', u'http://www.linuxjournal.com/taxonomy/term/17/0/feed'),
    (u'Sysadmin', u'http://www.linuxjournal.com/taxonomy/term/21/0/feed'),
    (u'Webmaster', u'http://www.linuxjournal.com/taxonomy/term/24/0/feed')]

    def append_page(self, soup, appendtag):
        next = appendtag.find('li', attrs={'class': 'pager-next'})
        while next:
            nexturl = next.a['href']
            appendtag.find('div', attrs={'class': 'links'}).extract()
            soup2 = self.index_to_soup('http://www.linuxjournal.com' + nexturl)
            pagetext = soup2.find(
                attrs={'class': 'node-inner'}).find(attrs={'class': 'content'})
            next = appendtag.find('li', attrs={'class': 'pager-next'})
            comments = pagetext.findAll(
                text=lambda text: isinstance(text, Comment))
            for comment in comments:
                comment.extract()
            pos = len(appendtag.contents)
            appendtag.insert(pos, pagetext)
        tag = appendtag.find('div', attrs={'class': 'links'})
        if tag:
            tag.extract()

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