'''

@author: olivier.massot, 2018
'''
from core.validation import NetgeoValidator, DuplicatedPk, RelationError
from schemas.netgeo_2_2_doe.models import Artere, Cable, Equipement, Noeud, \
    Tranchee, Zapbo


class Netgeo22DoeValidator(NetgeoValidator):
    schema_name = "Netgeo v2.2 DOE"
    models = [Artere, Cable, Equipement, Noeud, Tranchee, Zapbo]
    
    def _technical_validation(self):
        
        # construction de l'index
        self.index = {}
        for model in self.dataset:
            self.index[model] = {}
            
            for item in self.dataset[model]:
                pk_value = getattr(item, model.pk)
                if pk_value in self.index[model]:
                    self.log_error(DuplicatedPk("Doublons dans le champs", filename=model.filename, field=model.pk))
                else:
                    self.index[model][pk_value] = item
            
        del self.dataset
             
        if self.errors: 
            return
            
        # rattachement les noeuds aux artères     
        for artere in self.index[Artere]:
            try:
                artere.noeud_a = self.index[Artere][artere.AR_NOEUD_A]
            except KeyError:
                self.log_error(RelationError("Le noeud '{}' n'existe pas".format(artere.AR_NOEUD_A), filename=Artere.filename, field="AR_NOEUD_A"))
                
            try:
                artere.noeud_b = self.index[Artere][artere.AR_NOEUD_B]
            except KeyError:
                self.log_error(RelationError("Le noeud '{}' n'existe pas".format(artere.AR_NOEUD_B), filename=Artere.filename, field="AR_NOEUD_A"))
        
        # rattachement des equipements aux cables
        for cable in self.index[Cable]:
            try:
                cable.equipement_a = self.index[Cable][cable.CA_EQ_A]
            except KeyError:
                self.log_error(RelationError("L'équipement '{}' n'existe pas".format(cable.AR_NOEUD_A), filename=Cable.filename, field="CA_EQ_A"))
                
            try:
                cable.equipement_b = self.index[Cable][cable.CA_EQ_B]
            except KeyError:
                self.log_error(RelationError("L'équipement '{}' n'existe pas".format(cable.AR_NOEUD_B), filename=Cable.filename, field="CA_EQ_B"))
                
        if self.errors: 
            return
        
        # Contrôler dans la base si des éléments portant ces codes existent à des emplacements différents
        
        # Contrôler l'emprise des ZAPBO
        
        
        
    
if __name__ == "__main__":
    from core.constants import MAIN
    subject = MAIN / "work" / "AXIANS_082AP0_REC_180920.zip"
#     subject = MAIN / "work" / "STURNO_192AP1_REC_171211_OK"
    report = Netgeo22DoeValidator.submit(subject)
    print(report)
    