import sys, os, os.path, time, tempfile, uuid
import json

from django.core.management import setup_environ
from blinkster import settings

import lxml.etree

setup_environ(settings)

from ldt.ldt_utils.models import Media, Content


fp = open(os.path.join(os.path.dirname(os.path.abspath(__file__)),"update_db_0_19_to_0_20_content.json"), "r")
content_list = json.load(fp)

for content_src in content_list:
    #load iri
    #get iri path
    iri_path = os.path.join(settings.MEDIA_ROOT,"media/ldt",content_src['fields']['iri'])
    iri_doc = lxml.etree.parse(iri_path)
    
    duration = int(iri_doc.xpath("/iri/body/medias/media[@id='video']/video/@dur")[0])
    src = unicode(iri_doc.xpath("/iri/body/medias/media[@id='video']/video/@src")[0])

    media_list = Media.objects.filter(src=src)
    if(len(media_list) > 0):
        media = media_list[0]
    else:
        media = Media(src=src)
    media.update_date=content_src['fields']['update_date']
    media.creation_date=content_src['fields']['creation_date']
    media.title = content_src['fields']['title']
    media.description = content_src['fields']['description']
    media.duration = duration
    
    media.save()

    iri_id = content_src['fields']['iri_id']
    content_list = Content.objects.filter(iri_id=iri_id)
    
    if(len(content_list)>0):
        content = content_list[0]
    else:
        content = Content(iri_id=iri_id)
        
    content.iriurl = content_src['fields']['iri']
    content.title = content_src['fields']['title']
    content.description = content_src['fields']['description']
    content.duration = duration
    content.media_obj = media
                      
    content.save()

