__license__ = 'GPL v3'
__copyright__ = '2010-2019, Bobby Steel <bob at xdca.com>, Darko Miletic'
'''
www.thetimes.co.uk
'''
from mechanize import Request
from calibre import random_user_agent
from calibre.web.feeds.news import BasicNewsRecipe

import html5lib
from lxml import html


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


class TimesOnline(BasicNewsRecipe):
    title = 'The Times & Sunday Times (UK)'
    __author__ = 'Bobby Steel'
    description = 'news from United Kingdom and World'
    language = 'en_GB'
    publisher = 'Times Newspapers Ltd'
    category = 'news, politics, UK'
    excludeSections = ['Puzzles']
    oldest_article = 1
    max_articles_per_feed = 100
    no_stylesheets = True
    use_embedded_content = False
    encoding = 'utf-8'
    delay = 1
    needs_subscription = True
    publication_type = 'newspaper'
    INDEX = 'http://www.thetimes.co.uk/'
    LOGIN = 'https://login.thetimes.co.uk/'
    PREFIX = u'http://www.thetimes.co.uk'
    extra_css = """
        .author-name,.authorName{font-style: italic}
        .published-date,.multi-position-photo-text{font-family: Arial,Helvetica,sans-serif;
                                                    font-size: small; color: gray;
                                                    display:block; margin-bottom: 0.5em}
        body{font-family: Georgia,"Times New Roman",Times,serif}
    """

    conversion_options = {
        'comment': description,
        'tags': category,
        'publisher': publisher,
        'language': language}

    def get_cover_url(self):
        from datetime import date
        today = date.today()
        today_index = today.weekday()
        if (today_index == 6):  # Special cover on Sundays
            cover = 'https://cdn2-img.pressreader.com/pressdisplay/docserver/getimage.aspx?file=1163' + today.strftime(
                '%Y') + today.strftime('%m') + today.strftime(
                    '%d') + '00000000001001&page=1&scale=99'
            altcover = 'https://cdn2-img.pressreader.com/pressdisplay/docserver/getimage.aspx?file=1163' + today.strftime(
                '%Y') + today.strftime('%m') + today.strftime(
                    '%d') + '00000051001001&page=1&scale=99'
            # on some days cover is iterated using format here for altcover
        else:  # Mon-Thurs
            cover = 'https://cdn2-img.pressreader.com/pressdisplay/docserver/getimage.aspx?file=1148' + today.strftime(
                '%Y') + today.strftime('%m') + today.strftime(
                    '%d') + '00000000001001&page=1&scale=99'
            altcover = 'https://cdn2-img.pressreader.com/pressdisplay/docserver/getimage.aspx?file=1148' + today.strftime(
                '%Y') + today.strftime('%m') + today.strftime(
                    '%d') + '00000051001001&page=1&scale=99'
        self.log(cover)
        br = BasicNewsRecipe.get_browser(self)
        try:
            br.open(cover)
        except:
            cover = altcover
            br.open(cover)
        return cover

    def get_browser(self, *a, **kw):
        start_url = self.INDEX
        kw['user_agent'] = random_user_agent(allow_ie=False)
        br = BasicNewsRecipe.get_browser(self, *a, **kw)
        self.log('Starting login process...')
        res = br.open(start_url)
        sso_url = res.geturl()
        self.log(sso_url)
        request_query = {
            'username': self.username,
            'password': self.password,
            's': 1,
            'gotoUrl': self.INDEX,
        }
        rq = Request(self.LOGIN, headers={
            'Accept': 'text/html',
            'Accept-Language': 'en-US,en;q=0.8',
            'X-HTTP-Method-Override': 'POST',
            'X-Requested-With': 'XMLHttpRequest',
        }, data=request_query)
        self.log('Sending login request...')
        res = br.open(rq)
        return br

    remove_tags = [
        classes('is-hidden Toolbar Tooltip Topics Comments u-hide RelatedLinks ArticlePager Media-caption'),
        {'name': ['object', 'link', 'iframe', 'base', 'meta', 'script']},
    ]

    remove_attributes = ['lang']
    keep_only_tags = [{
        'attrs': {
            'id': ['article-main', 'bodycopy']}}, {
                'attrs': {
                    'class': ['Article Article--default', 'f-author']}}]
    remove_tags_after = dict(attrs={'class': 'Article-content'})

    feeds = [(u'All News', u'http://www.thetimes.co.uk/')]

    def preprocess_raw_html(self, raw, url):
        return html.tostring(
            html5lib.parse(raw, treebuilder='lxml', namespaceHTMLElements=False),
            method='html',
            encoding='unicode')

    def preprocess_html(self, soup):
        for item in soup.findAll(style=True):
            del item['style']
        return self.adeify_images(soup)

    def parse_index(self):
        soup = self.index_to_soup(self.INDEX)
        totalfeeds = []
        current_section = []
        div = []
        for div in soup.findAll('section', attrs={'data-text': True}):
            current_articles = []
            self.log('in section: ', div['data-text'])
            current_section = div['data-text']
            if current_section not in self.excludeSections:
                for article in div.findAll('div', attrs={'class': 'Item-content'}):
                    h3 = article.find('h3')
                    if h3 is not None:
                        title = self.tag_to_string(h3)
                        aurl = h3.find('a')
                        if aurl is not None:
                            url = aurl['href']
                            if url.startswith('/'):
                                url = 'http://www.thetimes.co.uk' + url
                            desc = title
                            self.log(
                                'section: ', current_section, 'title: ', title,
                                'url: ', url, 'desc: ', desc, '\n')
                            current_articles.append({
                                'title': title,
                                'url': url,
                                'description': desc})
                if current_articles:
                    totalfeeds.append((current_section, current_articles))
        return totalfeeds
