from html.parser import HTMLParser
import json

from django.core.cache import cache
import requests


def fetchJson(url):
    cached = cache.get(url)
    content = ""
    if not cached:
        r = requests.get(url)
        if(r.ok):
            cache.set(url, r.content)
            content = r.content
        else:
            # Write some proper error handling code here
            print ("Error - status code: " + r.status_code)  
    else:
        # Return the cached content
        content = cached

    return json.loads(content.decode('utf-8'))['VAL']

#HTML parser to get the info from the Orpheo XML
#Hopefully they'll update it because so far it's too slow
#to parse the xml and then the html..
#Better use extractFromJameSpot for now.
class MyHTMLParser(HTMLParser):
    
    def __init__(self):
        self.starttag=''
        self.endtag=''
        self.audio=''
        self.video=''
        self.images=[]
        self.captions=[]
        self.description=''
        self.captionList=''
        HTMLParser.__init__(self)
    
    def handle_starttag(self, tag, attrs):
        if (self.starttag == 'audio' and tag == 'source'):
            for attr in attrs:
                if 'src' in attr:
                    self.audio = attr[1]
        elif (tag == 'img'):
            for attr in attrs:
                if 'src' in attr:
                    self.images.append(attr[1])
        elif (tag == 'video'):
            for attr in attrs:
                if 'poster' in attr:
                    self.images.append(attr[1])
        if (self.starttag == 'video' and tag == 'source'):
            for attr in attrs:
                if 'src' in attr:
                    self.video = attr[1]
        self.starttag = tag
    def handle_endtag(self, tag):
        self.tag = tag
    def handle_data(self, data):
        if ('Caption_image' in data):
            self.captionList = True
        elif (self.captionList == True):
            self.captions.append(data)
        else:
            self.description = data