from ldt.utils.url import absolute_media_url, is_absolute
from ldt.ldt_utils.models import Content

def absolute_src_xml(doc):
    media_list = doc.xpath("/iri/medias/media")
    for element in media_list:
        src = element.get("src") #we split to hate two parts, one with the src
        if not is_absolute(src):
            new_src = absolute_media_url()+src
            element.set('src', new_src) #we replace the old value by the new one
    return doc

def relative_src_xml(ldt):
    modif = False
    no_more_media=False
    media_list = ldt.xpath("/iri/medias/media")
    if len(media_list) == 0 :
        no_more_media = True
    if not no_more_media :
        for element in media_list:
            src = element.get("src")
            id_content=element.get("id")
            content_list = Content.objects.filter(iri_id=id_content)
            if len(content_list) == 0:
                element.getparent().remove(element)
                modif = True
                for content_elem in ldt.xpath("/iri/annotations/content[@id=\"%s\"]" % id_content):
                    content_elem.getparent().remove(content_elem)
                media_list = ldt.xpath("/iri/medias/media")
                if len(media_list) == 0 :
                    no_more_media =  True
            else:
                content = content_list[0]
                right_src = content.relative_iri_url()
                if not src == right_src: #we will modify only the project that have an absolute url
                    modif = True
                    new_src = right_src
                    element.set('src', new_src) #we replace the old value by the new one

    return ldt, modif, no_more_media