#!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals

from calibre.web.feeds.news import BasicNewsRecipe


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


class Federalist(BasicNewsRecipe):
    title = 'The Federalist'
#	v4
    __author__ = 'Kovid Goyal'
    language = 'en'
    oldest_article = 10
    max_articles_per_feed = 100
    no_stylesheets = True
    encoding = 'utf-8'
    use_embedded_content = False
    remove_attributes = ['xmlns', 'lang', 'style', 'width', 'height']

    extra_css = """
        .shortbio,.article-excerpt{font-style: italic}
        .article-author-details,.article-author-description,.article-meta-author,.article-meta-date,.article-thumbnail-caption{font-size: small}
    """
    
    keep_only_tags = [
        classes('entry-header'),
        classes('title-lg wp-post-image post-categories article-excerpt article-author-details article-meta-author article-meta-date article-content article-body shortbio byline-month byline-standard alpha-byline article-author-description article-author-details'),
    ]
    remove_tags = [
        dict(name=['meta', 'link']),
        classes('auth-ad attachment-post-thumbnail attachment-author-bio'),
    ]

    feeds = [
        ('All', 'http://thefederalist.com/feed/'),
    ]

    def preprocess_html(self, soup):
        for img in soup.findAll('img', attrs={'data-lazy-src': True}):
            img['src'] = img['data-lazy-src']
        seen = set()
        for img in soup.findAll('img', src=True):
            src = img['src']
            if src in seen:
                img.extract()
            seen.add(src)
        return soup

    # Convert all links to blue text:
    def preprocess_html(self, soup):
        for a in soup.findAll('a', href=True):
            a.tag = 'span'
            a['style'] = 'color: blue'
            del a['href']
        return soup
 
# remove hypoerlink and retain text without formatting
# https://www.mobileread.com/forums/showthread.php?t=284965&highlight=remove+hyperlinks

    def postprocess_html(self, soup, first_fetch):
        for a in soup.findAll('a', href=True):
            del a['href']
        return soup