#!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
                        print_function)
import re
from calibre.web.feeds.news import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import Tag
import html5lib
from lxml.html import tostring
from css_selectors import Select


class NatGeo(BasicNewsRecipe):
    title = u'National Geographic'
    description = 'Daily news articles from The National Geographic'
    language = 'en'
    oldest_article = 20
    max_articles_per_feed = 25
    encoding = 'utf8'
    publisher = 'nationalgeographic.com'
    category = 'science, nat geo'
    __author__ = 'Kovid Goyal'
    masthead_url = 'http://s.ngeo.com/wpf/sites/themes/global/i/presentation/ng_logo_small.png'
    description = 'Inspiring people to care about the planet since 1888'
    timefmt = ' [%a, %d %b, %Y]'
    no_stylesheets = True
    use_embedded_content = False
    remove_attributes = ['style']

    feeds = [
        (u'Daily News', u'http://feeds.nationalgeographic.com/ng/News/News_Main')
    ]

    def parse_feeds(self):
        feeds = BasicNewsRecipe.parse_feeds(self)
        for feed in feeds:
            for article in feed.articles[:]:
                if 'Presented' in article.title or 'Pictures' in article.title:
                    feed.articles.remove(article)
        return feeds

    def preprocess_raw_html(self, raw_html, url):
        # BeautifulSoup does not parse the natgeo html correctly, so we use a
        # custom cleanup routine

        # NatGeo embeds huge inline svg images as interactive graphics, this
        # breaks conversion because split points cannot be found
        raw_html = re.sub(r'<svg.+?</svg>', '', raw_html, flags=re.DOTALL)
        root = html5lib.parse(
            raw_html, namespaceHTMLElements=False, treebuilder='lxml')
        select = Select(root)
        keep = tuple(select('.mainArt')) + tuple(select('.byline')
                                                 ) + tuple(select('#article__body'))
        body = root.xpath('//body')[0]
        for elem in keep:
            body.append(elem)
        for child in tuple(body.iterchildren('*')):
            if child not in keep:
                body.remove(child)
        for head in root.xpath('//head'):
            for child in tuple(head.iterchildren('*')):
                head.remove(child)
        return tostring(root, encoding=unicode)

    def preprocess_html(self, soup):
        for div in soup.findAll(attrs={'data-src': True, 'class': 'delayed-image-load'}):
            url = div['data-src']
            idx = url.find('.jpg/{width')
            if idx != -1:
                url = url[:idx + 4]
                img = Tag(soup, "img")
                img['src'] = url
                div.append(img)
        return soup
