// Hooks
import com.dvelop.d3.server.*
import com.dvelop.d3.server.core.D3Interface

// REST / Http
import javax.net.ssl.HttpsURLConnection
import groovy.json.JsonSlurper


class Eingangsrechnungsworkflow {

    // Constructor
    Eingangsrechnungsworkflow() {}

    @Entrypoint(entrypoint = "hook_insert_exit_30")
    @Condition(doctype = [ERwflProcessConstants.gDocType])
	int ProcessInsertExit30_1(D3Interface d3, Document doc, String fileDestination, Integer importOk, User d3User, DocumentType docType){
        
      def processId = ERwflProcessConstants.gProzessId;
      def baseUri = ERwflProcessConstants.gBaseUri;
      def repoId = ERwflProcessConstants.gRepoId;
	  def docId = doc.id;
	  def subject = ERwflProcessConstants.gSubject;
      def empfaengerBuchhaltung = ERwflProcessConstants.gBuchhaltung;
      def date = new Date();
      def timeString = date.getDateTimeString();
	  def businessKey = "${processId}-${timeString}-${docId}";
	  businessKey = businessKey.replaceAll(" ", "");

        
        def jsonBody = """{
            "businessKey": "${businessKey}",
				"variables": {
					"empfaengerBuchhaltung" : "${empfaengerBuchhaltung}",
					"formInstanceId" : "${businessKey}",
					"baseUri" : "${baseUri}",
					"docId" : "${docId}",
					"repoId" : "${repoId}",
					"subject" : "${subject}",
					"dv_attachment": "dmsObject:///dms/r/${repoId}/o2/${docId}"
				}
            }"""

		def migrationDoc = doc.field[48];
		
		if ( migrationDoc == null || migrationDoc == "" ){
			d3.log.info("ProcessInsertExit30_1 - Groovy hook insert_exit_30_1 " + doc.id + processId);
		
			validateGenericProcessStart( d3, doc, d3User, processId, jsonBody );
		}
        return 0
    }

    public static def validateGenericProcessStart(D3Interface d3, Document doc, User d3User, def processId, def jsonBody ) {

        try {
            def body = jsonBody;

            def http = new URL( ERwflProcessConstants.gBaseUri + "/process/processes/" + processId +  "/instances").openConnection() as HttpsURLConnection
            http.setRequestMethod('POST')
            http.setDoOutput(true)
            http.setRequestProperty("Content-Type", "application/json; charset=utf-8")
            http.setRequestProperty("Authorization", "Bearer " + ERwflProcessConstants.gApiKey )
			http.setRequestProperty("Accept-Charset" , "utf-8")

            http.outputStream.write(body.getBytes("UTF-8"))
            http.connect()

            def response = [:]    

            if (http.responseCode == 200 || http.responseCode == 201) {
				def location = http.getHeaderField("location");
                d3.log.info("Process was started: " + location);
				d3.log.info("Process was started on: " + http);
				d3.log.info("Process was started on baseUri: " + ERwflProcessConstants.gBaseUri );
            } else {
                response =  http.getResponseMessage()
                d3.log.error("Error while starting process: " + response + "(" + http.responseCode + ")");
				d3.log.error("POST-Request send: " + http + "(" + http.responseCode + ")");
                return -1;
            }
        } catch (Exception e) {
            d3.log.error("Exception while starting process: " + e.getMessage());
            return -1;
        }

        return 0;
    }
}
