
import json

import requests
import xmltodict

from ammicosrv.ammico.utils import fetchJson, MyHTMLParser


def extractFromMIMO(slide):
    details = {}
    params = {'of': 'json', 'q': 'record_inventorynumber:' + slide.id_inventory} 
    data = requests.get(slide.book.exposition.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(slide.book.exposition.url_jamespot + '&f=list&o=article&type=stop&itemFormat=article')
    for stops in stopList:
        if (slide.id_stop == 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.id_stop.replace('stop-', '')} 
    data = requests.get(slide.book.exposition.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'],
            'id_inventory': 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