#!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
from calibre.web.feeds.news import BasicNewsRecipe

'''
www.autosport.com
'''

class AutosportUserRecipe(BasicNewsRecipe):
    language = 'en_GB'
    description = u'Smart insight. Published daily. The in-depth, independent F1 analysis you deserve.'
    masthead_url = 'http://cdn.images.autosport.com/asdotcom.gif'
    remove_empty_feeds = True
    __author__ = 'Pacha2 using Autosport.com'
    needs_subscription = True
    title          = 'Autosport Plus'
    publication_type = 'magazine'
    oldest_article = 7
    max_articles_per_feed = 100
    auto_cleanup   = True
    remove_javascript = True
    ignore_duplicate_articles = {'title', 'url'}
    
    def get_browser(self):
        from mechanize import Request
        import json
        br = BasicNewsRecipe.get_browser(self)
        if self.username is not None and self.password is not None:
            # Authentication
            user_agent ='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'  
            br.addheaders = [('content-type', 'application/json'),('User-Agent', user_agent),('Referer','https://www.autosport.com/')]
            br.open('https://www.autosport.com')
            cred = b'{"login":"email_placeholder","password":"pass_placeholder","recaptchaResponse":""}'
            cred = cred.replace("email_placeholder", self.username )
            cred = cred.replace("pass_placeholder", self.password )
            login_url = 'https://id.tinypass.com/id/api/v1/identity/login/token?aid=cxPw94Eaz6&lang=en_US'
            rq = Request(login_url, headers={
                'Content-Type': 'application/json',
                'user-agent': user_agent,
            }, data=cred)
            access_token_resp = br.open(rq).read()
            print ("Access Token Response " + access_token_resp)
            atj = json.loads(access_token_resp)
            access_token=atj['access_token']
            print ("Just the Access Token " + str(access_token))
            jax=br.open('https://buy.tinypass.com/api/v3/access/token/list?url=https%3A%2F%2Fwww.autosport.com%2F&aid=cxPw94Eaz6&user_provider=piano_id&user_token='+ access_token).read()
            br.open('https://id.tinypass.com/id/api/v1/identity/vxauth/cookie?client_id=cxPw94Eaz6&token='+ access_token)
            jaxj = json.loads(jax)
            tac = jaxj['access_token_list']['value']
            print ("Authorised tac " + tac)
            br.set_simple_cookie('__tac', tac, '.autosport.com', path='/')
            br.set_simple_cookie('__utp', access_token, '.autosport.com', path='/')
        return br
    
    def get_cover_url(self):
        from datetime import date, timedelta
        ## Calculate Date logic for cover Image
        today = date.today()
        dow=today.isoweekday()
        if dow < 4:
            offdow=dow+3
        if dow >= 4:
            offdow=dow-4
        jpgdate=today - timedelta(days=offdow)
        autosport_cover = 'http://digitaledition.autosport.com/issue/'+ jpgdate.strftime('%Y') + '/covers/' + jpgdate.strftime('%d%m%Y') + '.jpg'
        return autosport_cover
    
    def check_words(words):
        return lambda x: x and frozenset(words.split()).intersection(x.split())
    

    feeds          = [
        ('Formula 1', 'https://www.autosport.com/rss/feed/f1'),
        ('Features', 'https://www.autosport.com/rss/feed/features'),
        ('All News', 'https://www.autosport.com/rss/feed/all'),
    ]
    
    