
import json

import requests
import xmltodict

from ammico.utils import fetchJson, MyHTMLParser
from django.conf import settings


def extractFromMIMO(slide):
    details = {}
    params = {'of': 'json', 'q': 'record_inventorynumber:' + slide.idInventory}
    data = requests.get(settings.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(settings.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(settings.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
