# -*- coding: utf-8 -*-
'''
Created on Apr 15, 2013

@author: tc
'''

from ..utils import show_progress
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.db.models import signals
from ldt.ldt_utils.contentindexer import index_project
from ldt.ldt_utils.models import Content, Project
import lxml.etree #@UnresolvedImport


class Command(BaseCommand):
    '''
    Updates iri files's url in project ldt xml
    '''

    help = "Updates iri files's url in project ldt xml"
    
    
    def __safe_get(self, dict_arg, key, conv = lambda x: x, default= None):
        val = dict_arg.get(key, default)
        return conv(val) if val else default

    def __safe_decode(self, s):
        if not isinstance(s, basestring):
            return s
        try:
            return s.decode('utf8')
        except:
            try:
                return s.decode('latin1')
            except:
                return s.decode('utf8','replace')

    def handle(self, *args, **options):
        # We avoid a useless reindex
        signals.post_save.disconnect(index_project, sender=Project)
        # We begin...
        writer = None
        i = 0
        print("Loading datas...")
        projects = Project.objects.all().prefetch_related('contents')
        total = len(projects)
        for p in projects:
            i += 1
            writer = show_progress(i, total, "project : %s" % (p.title), 50, writer)
            # Get ldt xml
            ldt = None
            try:
                ldt = lxml.etree.fromstring(p.ldt_encoded)
            except:
                # Unable to read xml.
                continue
            # Get content id
            result = ldt.xpath("/iri/medias/media")
            for medianode in result:
                # We loop on p.contents because they have already been loaded in the orm request
                # Requesting Content.objects.get() would cost too many db requests
                content_iri_id = medianode.get("id")
                for content in p.contents.all():
                    if content.iri_id == content_iri_id:
                        medianode.set('src', content.iri_url())
                        break
            # All iri urls have been updated, we can save the project
            p.ldt = lxml.etree.tostring(ldt, pretty_print=True)
            with transaction.commit_on_success():
                p.save()
        # This is the end
        signals.post_save.connect(index_project, sender=Project)
        print("This is the end")
        
        