from django.core.management.base import BaseCommand
from ldt.ldt_utils.models import Content, Project
from ldt.utils.projectldt_parser import relative_src_xml
import lxml.etree

class Command(BaseCommand):
    help = 'set the .iri src in relative url'
    
    def handle(self, *args, **options):
        project_list = Project.objects.all()
        for p in project_list: #we check all the project in the database
            no_more_media = False
            modif = False
            try : 
                iri = lxml.etree.fromstring(p.ldt)
            except :
                iri = None
                p.delete()
            if iri is not None :
                new_ldt, modif, no_more_media = relative_src_xml(iri)
                if modif and not no_more_media:
                    new_ldt = lxml.etree.tostring(new_ldt, pretty_print=True)
                    p.ldt= new_ldt #we write the the new xml 
                    p.save()
                if no_more_media :
                    p.delete()