// Global d.3 libraries -------------------------------------------------------
import com.dvelop.d3.server.core.D3;
import com.dvelop.d3.server.core.D3Interface;
import com.dvelop.d3.server.Document;
import com.dvelop.d3.server.User;
import com.dvelop.d3.server.DocumentType;
// Libraries to handle the different hook types ---------------------------------------------------
import com.dvelop.d3.server.Entrypoint;
import com.dvelop.d3.server.Condition;
// Libraries to handle the different hook types --------------------------------
import com.dvelop.d3.server.Validation
import com.dvelop.d3.server.ValueSet;
import com.dvelop.d3.server.RepositoryField;
import com.dvelop.d3.server.Translation;
import com.dvelop.d3.server.ValueSetTranslation;

// Special libraries -----------------------------------------------------------------------------
import groovy.sql.Sql;
import javax.net.ssl.HttpsURLConnection;
import groovy.json.JsonOutput;
import groovy.json.JsonSlurper;
import groovy.transform.Field;


class d3ValueSets {	
	
    // Wertemenge fuer Benutzer
    @ValueSet (entrypoint = "vsUserIDP")
    def getUserIDPID( D3 d3, RepositoryField reposField, User user, DocumentType docType, int  rowNo, int  validate, Document doc )
    {
        /*
        try {
            //Auslesen der IDP Benutzer IDs
            HttpsURLConnection idpRequest = new URL(Defs.baseURi + "/identityprovider/scim/users").openConnection();
            idpRequest.requestMethod = "GET";
            idpRequest.setRequestProperty("Origin", Defs.baseURi);
            idpRequest.setRequestProperty("Authorization", "Bearer " + Defs.ServiceAPIKey);
            idpRequest.setRequestProperty("Accept", "application/json");
            def response = idpRequest.getInputStream().getText();
             
            def jsonSlurper = new JsonSlurper()
            def responseObject = jsonSlurper.parseText(response.toString())
             
            initValueSetValues(d3, reposField, responseObject.resources.collect { it.get("id") }, "vsUserIDP")
 
        }catch(Exception e) {
            d3.log.error("###-> Returnwert Fehler Ermittlung IDPId " + e.getMessage())
        }
		*/
		
		String sql, fieldValue, fieldValue2
		int fieldPos
		
		fieldValue = ""
		
		fieldPos= reposField.getPreferedFieldNumber().toInteger()
				
		if (fieldPos >= 60 && fieldPos <= 69)
		{
			fieldValue = doc.field[fieldPos][rowNo]
		}
		else
		{
			fieldValue = doc.field[fieldPos]
		}
		
		if (!(fieldValue) || fieldValue.length() < 3)
		{
			reposField.provideValuesForValueSet(["Please enter at least 3 characters."])
		}
		else
		{
			fieldValue2 = "%" + fieldValue + "%"
			
			sql = """SELECT distinct top 50 idp_id as userid from benutzer
					 WHERE (realname like ? or idp_id = ?)"""
					 
			def resultList = d3.sql.executeAndGet(sql, [fieldValue2, fieldValue])
			
			initValueSetValues(d3, reposField, resultList.collect { it.get("userid") }, "vsUserIDP")
		}
         
        return 0
    }
     
    // Wertemenge fuer Benutzer
    @ValueSetTranslation (entrypoint = "vsUserIDP")
    def getUserIDPIDTranslation(D3Interface d3, Translation transl)
    {
         /* 16.11.2023: Commented out as this is too slow for high amounts of users
         try {
            //Auslesen der IDP Benutzer IDs
            HttpsURLConnection idpRequest = new URL(Defs.baseURi + "/identityprovider/scim/users").openConnection();
            idpRequest.requestMethod = "GET";
            idpRequest.setRequestProperty("Origin", Defs.baseURi);
            idpRequest.setRequestProperty("Authorization", "Bearer " + Defs.ServiceAPIKey);
            idpRequest.setRequestProperty("Accept", "application/json");
            def response = idpRequest.getInputStream().getText();
             
            def jsonSlurper = new JsonSlurper()
            Map parsedJson = jsonSlurper.parseText(response.toString()) ;
            def array1 = parsedJson.get("resources");
            List<String> idpval =  new ArrayList<String>();
            Map<String, String> idpvalall = new HashMap<String, String>();
            String strMapValue = "" ;
                 
            for(def member : array1) {                                     
                strMapValue = member.displayName  ;
                idpval.add( member.id );
                idpvalall.put (  member.id , new String(strMapValue.getBytes(), "UTF-8") );
                }
            transl.set(idpvalall);
 
            }catch(Exception e) {
            d3.log.error("###-> Returnwert Fehler Ermittlung IDPId " + e.getMessage())
        }
		*/
		
		String sql
		
		sql = "SELECT distinct realname as username, idp_id as userid  from benutzer"

		def resultList = d3.sql.executeAndGet(sql)
        resultList.each{ transl.set(it["userid"], it["username"]) }
		
        return 0
         
    }
	
	
	// Hilfsfunktion zur Uebersetzung von Wertemengen
    private void initValueSetValues(D3Interface d3, RepositoryField repoField, Iterable<String> valueKeys, String valueSetId) {
        repoField.provideValuesForValueSet(valueKeys)
        d3.getArchive().removeTranslationFromCache(valueSetId, Locale.GERMAN)
        d3.getArchive().removeTranslationFromCache(valueSetId, Locale.ENGLISH)
    }
}
