from html.parser import HTMLParser
import json

import requests
from rest_framework import serializers
import xmltodict

from ammico.models import Book, Slide
from ammico.utils import fetchJson
from config import URL_EXALEAD, URL_ORPHEO, URL_JAMESPOT


class BookSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Book
        fields = ('id', 'user', 'idArticle', 'parent_visit', 'title', 'description', 'image', 'date')
        
class SlideSerializer(serializers.ModelSerializer):
    details = serializers.SerializerMethodField('getStopInfo')
    index = serializers.SerializerMethodField('getOrder')
    
    def getStopInfo(self, slide):
        if (slide.idInventory != ""):
            #slide added from searched in MIMO database
            return extractFromMIMO(slide)
        else:
            #Get stop info from Oprheo
            #return extractFromOrpheo(slide)
            #Get stop info from Jamespot
            return extractFromJameSpot(slide)
        
    def getOrder(self, slide):
        return slide.book.get_slide_order().index(slide.id)

    class Meta:
        model = Slide
        fields = ('id', 'index', 'book', 'idStop', 'idInventory', 'title', 'description', 'image', 'date', 'favorite', 'details')
        

def extractFromMIMO(slide):
    details = {}
    params = {'of': 'json', 'q': 'record_inventorynumber:' + slide.idInventory} 
    data = requests.get(URL_EXALEAD, params=params)
    results = json.loads(data.content.decode('utf-8'))
    if (len(results['hits']) == 1):
        for i in results['hits'][0]['metas']:
            if('images' not in i):
                if ('name' in i):
                    details[i['name']] = i['value']
            else:
                details.setdefault('images', []).append(i['images'][0]['value'])
        details['title'] = details.pop('name')
    return details

def extractFromJameSpot(slide):
    details={}
    stopList = fetchJson(URL_JAMESPOT + '&f=list&o=article&type=stop&itemFormat=article')
    for stops in stopList:
        if (slide.idStop == stops['idStop']):
            details = stops
            details.setdefault('images', []).append(details.pop('firstImg'))
            details['description'] = details.pop('captionImg')
    return details

def extractFromOrpheo(slide):
    details = {}
    params = {'id': slide.idStop.replace('stop-', '')} 
    data = requests.get(URL_ORPHEO, params=params)
    parsed_data = xmltodict.parse(data.content.decode('utf-8'))
    
    if ('item' in parsed_data['result']):
        details = {
            'title': parsed_data['result']['item']['title'],
            'idInventory': parsed_data['result']['item']['Numero_inventaire'],
        }
        parser = MyHTMLParser()
        
        if (parsed_data['result']['item']['Description']):
            parser.feed(parsed_data['result']['item']['Description'])
            details['description']= parser.description
            
        if (parsed_data['result']['item']['Audio']):
            parser.feed(parsed_data['result']['item']['Audio'])
            details['images']= parser.images
            details['audio']= parser.audio
            details['captions']= parser.captions
            
        if (parsed_data['result']['item']['Video']):
            parser.feed(parsed_data['result']['item']['Video'])
            details['video']= parser.video
            details['images']= parser.images
            
        #if (parsed_data['result']['item']['Image']):
        #    parser.feed(parsed_data['result']['item']['Image'])
        #    details['image']= parser.caption
        
    return details

#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:
                    print(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