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

class Command(BaseCommand):
    help = 'set the .iri src in relative url'
    
    def handle(self, *args, **options):
        
        writer = None
        
        project_list = list(Project.objects.all())
        
        for i,p in enumerate(project_list): #we check all the project in the database
            
            writer = show_progress(i+1, len(project_list), "Processing project %s" % p.title, 80, writer)
            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(must_reindex=False)
                if no_more_media :
                    p.delete()