from calibre.web.feeds.news import BasicNewsRecipe
from collections import defaultdict

BASE = 'http://www.newsweek.com'


def href_to_url(a, add_piano=False):
    return BASE + a.get('href') + ('?piano_d=1' if add_piano else '')


def class_sels(*args):
    q = set(args)
    return dict(attrs={'class': lambda x: x and set(x.split()).intersection(q)})


class Newsweek(BasicNewsRecipe):

    title = 'Newsweek'
    __author__ = 'Kovid Goyal'
    description = 'Weekly news and current affairs in the US'
    language = 'en'
    encoding = 'utf-8'
    no_stylesheets = True
    requires_version = (1, 40, 0)

    keep_only_tags = class_sels(
        'article-header', 'article-body', 'header-image')
    remove_tags = [
        dict(name='meta'),
        class_sels(
            'block-openadstream', 'block-ibtmedia-social', 'issue-next',
            'most-popular', 'ibt-media-stories', 'user-btn-group',
            'trial-link', 'trc_related_container',
            'block-ibtmedia-top-stories'
        ),
        dict(id=['taboola-below-main-column', 'piano-root',
                 'block-nw-magazine-magazine-more-from-issue']),
    ]
    remove_attributes = ['style']

    def parse_index(self):
        root = self.index_to_soup(
            'http://www.newsweek.com/archive', as_tree=True)
        li = root.xpath(
            '//ul[contains(@class, "magazine-archive-items")]/li')[0]
        a = li.xpath('descendant::a[@href]')[0]
        url = href_to_url(a, add_piano=True)
        self.timefmt = self.tag_to_string(a)
        img = li.xpath('descendant::a[@href]/img[@src]')[0]
        self.cover_url = img.get('src')
        root = self.index_to_soup(url, as_tree=True)
        div = root.xpath(
            '//div[@id="block-nw-magazine-magazine-cover-story"]')[0]
        a = div.xpath('descendant::a[@href]')[0]
        index = [('Cover', [{'title': 'Cover story', 'url': href_to_url(a)}])]
        sections = defaultdict(list)
        div = root.xpath(
            '//div[@id="block-nw-magazine-magazine-issue-story-list"]')[0]
        for a in div.xpath('descendant::h3/a[@href and contains(@class, "article-link")]'):
            title = self.tag_to_string(a)
            li = a.xpath('ancestor::li')[0]
            desc = ''
            s = li.xpath('descendant::div[@class="summary"]')
            if s:
                desc = self.tag_to_string(s[0])
            sec = li.xpath('descendant::div[@class="category"]')
            if sec:
                sec = self.tag_to_string(sec[0])
            else:
                sec = 'Articles'
            sections[sec].append(
                {'title': title, 'url': href_to_url(a), 'description': desc})
            self.log(title, url)
            if desc:
                self.log('\t' + desc)
            self.log('')
        for k in sorted(sections):
            index.append((k, sections[k]))
        return index

    def print_version(self, url):
        return url + '?piano_d=1'

    def preprocess_html(self, soup):
        # Parallax images in the articles are loaded as background images
        # on <span> tags. Convert them to normal images.
        for span in soup.findAll('span', attrs={'class': lambda x: x and 'parallax' in x.split()}):
            s = span.find(style=True)
            if s is not None:
                url = s['style'].partition('(')[-1][:-1]
                s['style'] = 'display: block'
                s.name = 'img'
                s['src'] = url
        return soup
