
import json

import requests
import xmltodict

from ammicosrv.ammico.utils import fetchJson


def extractFromMIMO(slide):
    details = {}
    data = requests.get(slide.book.exposition.url_exalead_get_one + slide.research_id)
    results = json.loads(data.content.decode('utf-8'))
    if ('hits' in results and len(results['hits']) == 1):
        for hit in results['hits']:
            for i in hit['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')
    elif ('response' in results):
        for result in results['response'][0]['collect']:
            for key in result.keys():
                details[key.replace("_stop", "")] = result[key]
    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
"""
