@prefix adms: <http://www.w3.org/ns/adms#> .
@prefix dbo: <https://dbpedia.org/ontology/> .
@prefix dct: <http://purl.org/dc/terms/> .
@prefix locn: <http://www.w3.org/ns/locn#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix rr: <http://www.w3.org/ns/r2rml#> .
@prefix schema: <https://schema.org/> .
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix legal: <http://www.w3.org/ns/legal#> .
@prefix m8g: <http://data.europa.eu/m8g/> .

######## D2RML NAMESPACES ###########

@prefix dr: <http://islab.ntua.gr/ns/d2rml#> .
@prefix drop: <http://islab.ntua.gr/ns/d2rml-op#> .
@prefix dris: <http://islab.ntua.gr/ns/d2rml-is#> .

######## STIRDATA TMP NAMESPACES ###########

@prefix nuts-item: <http://data.europa.eu/nuts/code/> .
@prefix lau-item: <https://w3id.org/stirdata/resource/lau/item/> .

@prefix sd-voc: <https://w3id.org/stirdata/vocabulary/> .
@prefix sd-voc-adminlevel: <https://w3id.org/stirdata/resource/adminUnitLevel/> .

@prefix sd-agency-lv: <http://lv.data.stirdata.eu/resource/agency/> .
@prefix sd-organization-lv: <http://lv.data.stirdata.eu/resource/organization/> .
@prefix sd-unit-lv: <http://lv.data.stirdata.eu/resource/unit/> .
@prefix sd-site-lv: <http://lv.data.stirdata.eu/resource/site/> .
@prefix sd-address-lv: <http://lv.data.stirdata.eu/resource/address/> .
@prefix sd-identifier-lv: <http://lv.data.stirdata.eu/resource/identifier/> .

@prefix sd-companytype-item-lv: <http://lv.data.stirdata.eu/resource/companyType/item/> .
@prefix sd-companystatus-item-lv: <http://lv.data.stirdata.eu/resource/companyStatus/item/> .

######## EXECUTION ORDER ###########

<#Order>
   a dr:D2RMLSpecification ;
   dr:logicalDatasets ( 
#                        <#DCATMapping>
                        <#OrganizationsMapping> 
                        <#NutsMapping>
                      ) .

######## DATA SOURCES ###########

<#PostCodeSource>
   a dris:HTTPSource ;
   dris:cacheable true ;
   dris:uri "https://apps.islab.ntua.gr/geo/api/postcode?country-code={@@COUNTRY@@}&postcode={@@POSTCODE@@}" .
   
<#NutsSource>    
   a dris:HTTPSource ;
   dris:cacheable true ;
   dris:uri "https://stirdata-semantic.ails.ece.ntua.gr/api/content/index/nuts/search?text={@@TEXT@@}&fields=label&type=match&keys=notation" .

<#DCATSource> 
   a dris:HTTPSource ;
   dris:uri "https://data.europa.eu/api/hub/repo/datasets/4de9697f-850b-45ec-8bba-61fa09ce932f.ttl?useNormalizedId=true&locale=en" .

#<#BussinessRegistryOpenDataSource>
#   a dris:HTTPSource .

<#BussinessRegistryOpenDataSource>
   a dris:HTTPSource ;
   dris:uri "https://data.gov.lv/dati/dataset/4de9697f-850b-45ec-8bba-61fa09ce932f/resource/25e80bf3-f107-4ab4-89ef-251b5b9374e9/download/register.csv"  .

######## TRANSFORMATIONS ###########

<#PostCodeTransformation>
   dr:logicalArray [ 
      a dr:JSONItemArray ;
      dr:source <#PostCodeSource> ;
	  dr:iterator "$";
	  dr:limit 1;
   ] . 

<#NutsTransformation>
   dr:logicalArray [ 
      a dr:JSONItemArray ;
      dr:source <#NutsSource> ;
	  dr:iterator "$";
	  dr:limit 1;
   ] . 
   
######## AUXILIARY SOURCE ###########

<#AdminLevelModel>
    a dris:AuxiliaryModel .

######## MAIN DATASETS AND MAPPINGS ###########

<#DCATMapping>
   rr:logicalTable [
      a dr:SPARQLQueryResult ;
      dr:source <#DCATSource> ;
      dr:sparqlSelectQuery  "SELECT ?downloadURL WHERE { ?p a <http://www.w3.org/ns/dcat#Distribution> ; <http://www.w3.org/ns/dcat#accessURL> ?downloadURL . }" ;
   ] ;
   
   dr:triplesMap [
      dr:logicalOutput dris:CurrentD2RMLDocument ;
	  
	  rr:subject <#BussinessRegistryOpenDataSource> ;
	  
	  rr:predicateObjectMap [
	     rr:predicate dris:uri ;
		 rr:objectMap [
		    rr:column "downloadURL" ;
			rr:termType rr:Literal ;
		 ] ;
	  ] ;
   ] .


# ++ regcode
#    sepa
# ++ name
#    name_before_quotes
#    name_in_quotes
#    name_after_quotes
#    without_quotes
#    regtype
# -- regtype_text
# ++ type
# -- type_text
# ++ registered
# ++ terminated
# ++ closed
# ++ address
# ++ index
#    addressid
#    region
#    city
#    atvk
#    reregistration_term

<#OrganizationsMapping>  
   rr:logicalTable [ 
      a dr:CSVTable;
      dr:source <#BussinessRegistryOpenDataSource> ;
	  dr:headerRecord true;
	  dr:delimiter ";";
	  dr:quoteCharacter "\"";	  
#      dr:offset 1 ;
#	  dr:limit 5 ;
   ] ;
   
   dr:definedColumns (  
   [ 
      dr:name "ADDRESS_SPLIT" ;
      dr:function drop:extractMatch ; 
      dr:parameterBinding [ 
	     dr:parameter "input" ;
         rr:column "address"  ;
      ] ;
      dr:parameterBinding [
	     dr:parameter "regex" ;
         rr:constant "^(.*), (.*? (?:iela|gatve|prospekts|bulvaris|dambis|aleja|linija|�oseja|�kersiela|cel�|�kerslinija|laukums))\\s*(.*)?$"  ;
      ] ; 
   ]   
   ) ;

   dr:transformations ( 
   [
      dr:dataref <#PostCodeTransformation> ;
      dr:transformationName "PostCodeTransformation";
      dr:parameterBinding [ 
         dr:parameter "COUNTRY" ;
         rr:constant "LV" ;
      ] ;
      dr:parameterBinding [ 
         dr:parameter "POSTCODE" ;
         rr:template "LV-{index}" ;
         dr:condition [
            rr:column "index" ;
            drop:neq "";
         ] ; 		 
      ]  ;
   ]
   [
      dr:dataref <#NutsTransformation> ;
      dr:transformationName "NutsTransformation";
      dr:parameterBinding [ 
         dr:parameter "TEXT" ;
         rr:column "PostCodeTransformation~~$.NUTS3" ;
      ]  ;
   ]   ) ;   
   
   dr:triplesMap [
      # ID - CLASS
      rr:subjectMap [ 
         rr:template  "{@sd-organization-lv}{regcode}" ;
         rr:class legal:LegalEntity ;
      ] ;
   
#      # SYSTEM IDENTIFIER
#      rr:predicateObjectMap [ 
#         rr:predicate  dct:identifier ;
#         rr:objectMap  [ 
#            rr:column "regcode" ;
#            rr:termType  rr:Literal ;
#         ] ;
#      ] ; 

      # THIRD PARTY WEBPAGES ( NON-LINKED DATA )
      rr:predicateObjectMap [ 
         rr:predicate  schema:sameAs ;
#        rr:predicate  owl:sameAs ;
         rr:objectMap  [ 
            rr:template "https://www.ur.gov.lv/en/legal-entity/?id={regcode}" ;
            rr:termType rr:IRI ;
         ] ;
      ] ; 
   
      # UZ REGISTRATION IDENTIFIER
      rr:predicateObjectMap [
         rr:predicate legal:legalIdentifier ;
         rr:objectMap [
            rr:parentTriplesMap [
               rr:subjectMap [
                  rr:template "{@sd-identifier-lv}uz/{regcode}" ;
                  rr:class adms:Identifier ;
               ] ;

               # DATE ISSUED
               rr:predicateObjectMap [
                  rr:predicate dct:issued;
                  rr:objectMap [
                     rr:column "registered" ;
                     rr:datatype xsd:date;
                  ] ;
               ] ;

               # REGISTRATION NUMBER 
               rr:predicateObjectMap [
               rr:predicate skos:notation;
                  rr:objectMap [
                     rr:column "regcode" ;
                     rr:termType rr:Literal;
                  ] ;
               ] ;

               # ISSUING BODY
               rr:predicateObjectMap [
                  rr:predicate dct:creator;
                  rr:objectMap [
                     rr:constant sd-agency-lv:uz ;
                  ] ;
               ] ;
            ] ;
         ] ;
      ] ;    

      # COMPANY NAME
      rr:predicateObjectMap [ 
         rr:predicate  legal:legalName ;
         rr:objectMap  [ 
            rr:column "name" ;
            rr:termType  rr:Literal ;
         ] ;
      ] ;   
   
#     # JURISDICTION (ASSUME LATVIA FOR ALL) // check if
#     rr:predicateObjectMap [ 
#        rr:predicate  dbo:jurisdiction ;
#        rr:objectMap  [ 
#           rr:constant <http://publications.europa.eu/resource/authority/country/LVA> ;
#           rr:termType  rr:IRI ;
#        ] ;
#     ] ;     
   
      # LEGAL FORM (TEMPORARY UNTIL SKOS VOCABULARY DECIDED) -- 
      # IK, BDR, SIA, ZEM, IND, NOD, AKF, KAT, FIL, KB, PS, PAR, PSV, PPA, DRZ, AS, ARB, SKT, PAJ, UZN, GIM, SAB, ZVJ, PAP, ARA, PRV, LIG, KS, PP, ARV, SPO, VU, ROI, POR, KBS, SOU, ASF, SAA, SE, KOR, POL, SAV, SPA, PRO, KSS, REL, KBU, KLO, DIE, BAZ, 
      rr:predicateObjectMap [ 
         rr:predicate  legal:companyType ;
         rr:objectMap  [ 
            rr:template "{@sd-companytype-item-lv}{type}" ;
            rr:termType  rr:IRI ;
        ] ;
      ] ;   
	  
      # LEGAL STATUS (TEMPORARY UNTIL SKOS VOCABULARY DECIDED) -- 
      # Values in csv are : 
      # L	Aktivs likvidacijas process	Pending liquidation proceeding
      # R	Izslegts reorganizacijas rezultata	Removed from the register as a result of reorganization
      # A   Registered
      rr:predicateObjectMap [ 
         rr:predicate  legal:companyStatus ;
         rr:objectMap  [ 
            dr:cases ( [ 
               rr:template "{@sd-companystatus-item-lv}{closed}" ;
               rr:termType  rr:IRI ;
               dr:condition [
			      rr:column "closed" ;
				  drop:matches "[LR]";
			   ] 
			] [
               rr:template "{@sd-companystatus-item-lv}A" ;
               rr:termType  rr:IRI ;
            ] )
         ] ;
      ] ;	  
   
      # FOUNDATION DATE (use registration date)
      rr:predicateObjectMap [ 
         rr:predicate  m8g:registrationDate ;
         rr:objectMap  [ 
            rr:column "registered" ;
            rr:datatype xsd:date ;
         ] ;         
      ] ;  
   
      # DISOLUTION DATE (use terminated date)
      rr:predicateObjectMap [ 
         rr:predicate  schema:dissolutionDate ;
         rr:objectMap  [ 
            rr:column "terminated" ;
            rr:datatype xsd:date ;
         ] ;         
      ] ;          
   
      # ADDRESS 
      rr:predicateObjectMap [ 
         rr:predicateMap [
            rr:constant m8g:registeredAddress ;
            dr:condition [
               rr:column "index" ;
               drop:neq "";
            ] ;
         ] ;    
         rr:objectMap [
            rr:parentTriplesMap [
               rr:subjectMap [
                  rr:template "{@sd-address-lv}{regcode}";
                  rr:class locn:Address ;
               ] ;

               rr:predicateObjectMap [ 
                  rr:predicate  locn:fullAddress ;
                  rr:objectMap  [ 
                     rr:column  "address" ;
                     rr:termType  rr:Literal ;
                  ] ;
               ] ;

               rr:predicateObjectMap [ 
                  rr:predicate  locn:thoroughfare ;
                  rr:objectMap  [ 
                     rr:column "ADDRESS_SPLIT.match#2" ;
                     rr:termType  rr:Literal ;
                  ] ;      
               ] ;   

               rr:predicateObjectMap [ 
                  rr:predicate  locn:locatorDesignator ;
                  rr:objectMap  [ 
                     rr:column "ADDRESS_SPLIT.match#3" ;
                     rr:termType  rr:Literal ;
                  ] ;      
               ] ;   

               rr:predicateObjectMap [ 
                  rr:predicate  locn:postCode ;
                  rr:objectMap  [ 
                     rr:template "LV-{index}" ;
                     rr:termType  rr:Literal ;
                  ] ;      
               ] ;   

               rr:predicateObjectMap [ 
                  rr:predicate  locn:postName ;
                  rr:objectMap  [ 
                     rr:column "PostCodeTransformation~~$.LAU-native" ;
                     rr:termType  rr:Literal ;
                  ] ;      
               ] ;                       

               rr:predicateObjectMap [ 
                  rr:predicate  locn:adminUnitL1 ;
                  rr:objectMap  [ 
                     rr:constant "LV" ;
                     rr:termType  rr:Literal ;
                  ] ;      
               ] ;                    

               rr:predicateObjectMap [ 
                  rr:predicate  locn:adminUnitL2 ;
                  rr:objectMap  [ 
                     rr:column "NutsTransformation~~$.label[0]" ;
                     rr:termType  rr:Literal ;
                  ] ;
               ] ; 

               rr:predicateObjectMap [ 
                  rr:predicate  m8g:adminUnit ;
                  rr:objectMap  [ 
                     rr:constant <http://publications.europa.eu/resource/authority/country/LVA> ;
                     rr:termType  rr:IRI ;
                 ] ;    
               ] ;

               rr:predicateObjectMap [ 
                 rr:predicate  m8g:adminUnit ;
                 rr:objectMap  [ 
                    rr:template "{@nuts-item}{PostCodeTransformation~~$.NUTS3}" ;
                    rr:termType  rr:IRI ;
                 ]
               ] ;

               rr:predicateObjectMap [ 
                  rr:predicate  m8g:adminUnit ;
                  rr:objectMap  [ 
                     rr:template "{@lau-item}{PostCodeTransformation~~$.LAU}" ;
                     rr:termType  rr:IRI ;
                  ]
               ] ;
            ] ;
         ] ;
      ] ;
   ];
   
   dr:triplesMap [
      dr:logicalOutput <#AdminLevelModel> ;
      rr:subjectMap [ 
         rr:constant <http://publications.europa.eu/resource/authority/country/LVA> ;
         rr:class sd-voc-adminlevel:Country ;
      ] ;
   ] ;
   
   dr:triplesMap [
      dr:logicalOutput <#AdminLevelModel> ;
      rr:subjectMap [ 
         rr:template "{@nuts-item}{PostCodeTransformation~~$.NUTS3}";
         rr:class sd-voc-adminlevel:NUTS-3 ;
      ] ;
   ] ;
   
   dr:triplesMap [
      dr:logicalOutput <#AdminLevelModel> ;
      rr:subjectMap [ 
         rr:template "{@lau-item}{PostCodeTransformation~~$.LAU}" ;
         rr:class sd-voc-adminlevel:LAU ;
      ] ;
   ] .

<#NutsMapping>
   rr:logicalTable [ 
      dr:source <#AdminLevelModel> ;
      dr:sparqlQuery "SELECT ?uri ?type WHERE { ?uri a ?type } "; 
   ] ;
   
   dr:triplesMap[ 
      rr:subjectMap [ 
         rr:column "uri";
         rr:class m8g:AdminUnit ;
      ] ;

      rr:predicateObjectMap [ 
         rr:predicate  m8g:code ;
         rr:objectMap  [ 
            rr:column "uri" ;
            rr:termType  rr:IRI ;
         ]
      ] ;   

      rr:predicateObjectMap [ 
         rr:predicate  m8g:level ;
         rr:objectMap  [ 
            rr:column "type" ;
            rr:termType rr:IRI ;
         ]
      ] ;   
   ] .
   
   
