/*------------------------------------------------------------------------
   File        : getAdresseByKnrImpl
   Purpose     : 
   Syntax      : 
   Description : 
   Author(s)   : walter.riechsteiner
   Created     : Wed May 29 21:02:53 CEST 2024
   Notes       : 
 ----------------------------------------------------------------------*/

BLOCK-LEVEL ON ERROR UNDO, THROW.

USING OpenEdge.Net.HTTP.IHttpResponse FROM PROPATH.
USING OpenEdge.Net.HTTP.StatusCodeEnum FROM PROPATH.
USING OpenEdge.Web.IWebRequest FROM PROPATH.
USING OpenEdge.Web.WebHandler FROM PROPATH.
USING OpenEdge.Web.WebResponseWriter FROM PROPATH.
USING Progress.Json.ObjectModel.JsonObject FROM PROPATH.
USING Progress.Json.ObjectModel.JsonArray FROM PROPATH.
USING src.ch.adprime.gemis.WebHandlerUtilities FROM PROPATH.

CLASS getAdresseByKnrImpl INHERITS WebHandler:

    { adressen/ttadresse.i }

    METHOD PUBLIC LOGICAL createJsonStructur(INPUT iphBuffer AS HANDLE, OUTPUT lcStruktur AS LONGCHAR):
        DEFINE VARIABLE i      AS INTEGER   NO-UNDO.
        DEFINE VARIABLE hFeld  AS HANDLE    NO-UNDO.
        DEFINE VARIABLE cZeile AS CHARACTER NO-UNDO.

        MESSAGE "Entering createJsonStructur" VIEW-AS ALERT-BOX.

        lcStruktur = CHR(123) + CHR(10) + '  "fields": [' + CHR(10).

        DO i = 1 TO iphBuffer:NUM-FIELDS:
            hFeld = iphBuffer:BUFFER-FIELD(i).
            IF hFeld:EXTENT > 0 THEN NEXT.
            cZeile = SUBSTITUTE('    &5"name": "&1", "type": "&2", "label": "&3", "value": "&4" &6',
                hFeld:NAME, "text", (IF hFeld:LABEL <> "" THEN hFeld:LABEL ELSE hFeld:NAME), hFeld:BUFFER-VALUE, CHR(123), CHR(125)).
            lcStruktur = lcStruktur + cZeile.
            IF i <> iphBuffer:NUM-FIELDS THEN lcStruktur = lcStruktur + ','.
            lcStruktur = lcStruktur + CHR(10).
        END.
        lcStruktur = lcStruktur + '  ]' + CHR(10) + CHR(125) + CHR(10).

        MESSAGE "Exiting createJsonStructur" VIEW-AS ALERT-BOX.

        RETURN TRUE.
    END METHOD.

    METHOD OVERRIDE PROTECTED INTEGER HandlePost(INPUT poRequest AS IWebRequest):
        DEFINE VARIABLE oResponse    AS IHttpResponse     NO-UNDO.
        DEFINE VARIABLE oWriter      AS WebResponseWriter NO-UNDO.
        DEFINE VARIABLE oJsonData    AS JsonObject        NO-UNDO.
        DEFINE VARIABLE ipCompanyID  AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE ipCustomerID AS INTEGER           NO-UNDO.
        DEFINE VARIABLE lcJsonString AS LONGCHAR          NO-UNDO.
        DEFINE VARIABLE httAdresse   AS HANDLE            NO-UNDO.
        DEFINE VARIABLE lRetVal      AS LOGICAL           NO-UNDO.
        DEFINE VARIABLE cSearchType  AS CHARACTER         NO-UNDO INITIAL "Knr".
        DEFINE VARIABLE cWortIndex   AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE iPage        AS INTEGER           NO-UNDO INITIAL 1.
        DEFINE VARIABLE iPageSize    AS INTEGER           NO-UNDO INITIAL 10.
        DEFINE VARIABLE cGetHtml     AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE lcHTML       AS LONGCHAR          NO-UNDO.
        DEFINE VARIABLE cDatei       AS CHARACTER         NO-UNDO.

        MESSAGE "Entering HandlePost" VIEW-AS ALERT-BOX.
        
        lRetVal = WebHandlerUtilities:getJsonFromRequest(INPUT poRequest, OUTPUT oJsonData) NO-ERROR.
        MESSAGE 'getJsonFromRequest = ' lRetVal.

        IF lRetVal THEN 
        DO:
            cGetHtml     = oJsonData:GetCharacter("gethtml")        NO-ERROR.
            ipCompanyID  = oJsonData:GetCharacter("companyID")      NO-ERROR.
            ipCustomerID = oJsonData:GetInteger("customerID")       NO-ERROR.
            cSearchType  = oJsonData:GetCharacter("searchType")     NO-ERROR.
            cWortIndex   = oJsonData:GetCharacter("WortIndex")      NO-ERROR.
            iPage        = oJsonData:GetInteger("page")             NO-ERROR.
            iPageSize    = oJsonData:GetInteger("pageSize")         NO-ERROR.
            
            MESSAGE 'gethtml = ' cGetHtml ' companyID = ' ipCompanyID ' customerID = ' ipCustomerID ' SearchType = ' cSearchType ' WortIndex = ' cWortIndex ' page = ' iPage ' pageSize = ' iPageSize.

            IF cGetHtml = 'gethtml' THEN 
            DO:
                cDatei = 'html/adressen.html'.
                cDatei = SEARCH(cDatei).
                MESSAGE cDatei.
                
                COPY-LOB FILE 'C:\Entwicklung\Ge_MIS\pasoeGEMIS\webapps\ADRESSEN\WEB-INF\openedge\html/adressen.html' TO lcHTML.
                oResponse = NEW OpenEdge.Web.WebResponse().
                oResponse:StatusCode = INTEGER(StatusCodeEnum:OK).
                oResponse:ContentType = "text/html;charset=utf-8".
                oWriter = NEW WebResponseWriter(oResponse).
                oWriter:Open().
                MESSAGE 'lcString Rückgabe: ' + STRING(lchtml) VIEW-AS ALERT-BOX.
                oWriter:Write(lcHTML).
                oWriter:Close().
                RETURN 200.
            END.
            
            IF cSearchType = "name" THEN 
            DO:
                RETURN getAdressenByWortIndex(poRequest, cWortIndex, ipCompanyID, iPage, iPageSize).
            END.
            
            EMPTY TEMP-TABLE ttAdresse.

            FIND Adresse NO-LOCK
                WHERE Adresse.Firma = ipCompanyID
                AND   Adresse.Knr   = ipCustomerID NO-ERROR.
            IF AVAILABLE Adresse THEN 
            DO:
                CREATE ttAdresse.
                BUFFER-COPY Adresse TO ttAdresse.
                MESSAGE 'Address found and copied to ttAdresse' VIEW-AS ALERT-BOX.
            END.
            ELSE 
            DO:
                MESSAGE 'Address not found' VIEW-AS ALERT-BOX.
            END.

            httAdresse = TEMP-TABLE ttAdresse:DEFAULT-BUFFER-HANDLE.
            oJsonData = NEW JsonObject().
            httAdresse:WRITE-JSON('JsonObject', oJsonData).
            oJsonData:WRITE(lcJsonString, TRUE).
        END.
        ELSE 
        DO:
            MESSAGE 'Fehler beim Abrufen der Daten' VIEW-AS ALERT-BOX.
        END.

        oResponse = NEW OpenEdge.Web.WebResponse().
        oResponse:StatusCode = INTEGER(StatusCodeEnum:OK).
        oResponse:ContentType = "application/json;charset=utf-8".
        oWriter = NEW WebResponseWriter(oResponse).
        oWriter:Open().
        MESSAGE 'lcString Rückgabe: ' + STRING(lcJsonString) VIEW-AS ALERT-BOX.
        oWriter:Write(lcJsonString).
        oWriter:Close().

        MESSAGE "Exiting HandlePost" VIEW-AS ALERT-BOX.

        CATCH e AS Progress.Lang.Error:
            MESSAGE "Exception occurred: " + e:GetMessage(1) VIEW-AS ALERT-BOX ERROR BUTTONS OK.
            RETURN -1.
        END CATCH.
    END METHOD.

    METHOD PUBLIC INTEGER getSuggestions(INPUT poRequest AS IWebRequest):
        DEFINE VARIABLE cWortIndex  AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cParams     AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cParam      AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cFeld       AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cWert       AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE ii          AS INTEGER           NO-UNDO.
        DEFINE VARIABLE oJsonArray  AS JsonArray         NO-UNDO.
        DEFINE VARIABLE oJsonObject AS JsonObject        NO-UNDO.
        DEFINE VARIABLE oResponse   AS IHttpResponse     NO-UNDO.
        DEFINE VARIABLE oWriter     AS WebResponseWriter NO-UNDO.
        DEFINE VARIABLE lRetVal     AS LOGICAL           NO-UNDO.

        MESSAGE "Entering getSuggestions" VIEW-AS ALERT-BOX.

        lRetVal = WebHandlerUtilities:getAllKeysFromHeader(INPUT poRequest, OUTPUT cParams) NO-ERROR.
        MESSAGE 'getAllKeysFromHeader = ' lRetVal VIEW-AS ALERT-BOX.

        DO ii = 1 TO NUM-ENTRIES(cParams, '&'):
            cParam = ENTRY(ii, cParams, '&').
            cFeld = ENTRY(1, cParam, '=').
            cWert = ENTRY(2, cParam, '=').
            MESSAGE 'Parameter: ' cFeld ' = ' cWert VIEW-AS ALERT-BOX.

            CASE cFeld:
                WHEN 'WortIndex' THEN
                    cWortIndex = cWert.
            END CASE.
        END.

        EMPTY TEMP-TABLE ttAdresse.

        FOR EACH Adresse NO-LOCK
            WHERE Adresse.WortIndex BEGINS cWortIndex:
            CREATE ttAdresse.
            BUFFER-COPY Adresse TO ttAdresse.
        END.

        oJsonArray = NEW JsonArray().
        FOR EACH ttAdresse NO-LOCK:
            oJsonObject = NEW JsonObject().
            oJsonObject:Add("Knr", ttAdresse.Knr).
            oJsonObject:Add("Anzeig_br", ttAdresse.Anzeig_br).
            oJsonArray:Add(oJsonObject).
        END.

        oResponse = NEW OpenEdge.Web.WebResponse().
        oResponse:StatusCode = INTEGER(StatusCodeEnum:OK).
        oResponse:ContentType = "application/json;charset=utf-8".

        DEFINE VARIABLE lcString AS LONGCHAR NO-UNDO.
        oJsonArray:WRITE(lcString, FALSE).

        COPY-LOB lcString TO FILE 'C:\TEMP\Json.txt'.

        oWriter = NEW WebResponseWriter(oResponse).
        oWriter:Open().
        /*    oWriter:Write(oJsonArray:ToString()).*/
        MESSAGE 'lcString Rückgabe: ' + STRING(lcString) VIEW-AS ALERT-BOX.        
        oWriter:Write(lcString).
        oWriter:Close().


        MESSAGE "Exiting getSuggestions" VIEW-AS ALERT-BOX.

        RETURN 0.
    END METHOD.

    METHOD PUBLIC INTEGER getAdressenByWortIndex(INPUT poRequest AS IWebRequest, cWortIndex AS CHARACTER, cCompanyID AS CHARACTER, iPage AS INTEGER, iPageSize AS INTEGER):
        DEFINE VARIABLE ii          AS INTEGER           NO-UNDO.
        DEFINE VARIABLE oJsonArray  AS JsonArray         NO-UNDO.
        DEFINE VARIABLE oJsonObject AS JsonObject        NO-UNDO.
        DEFINE VARIABLE oResponse   AS IHttpResponse     NO-UNDO.
        DEFINE VARIABLE oWriter     AS WebResponseWriter NO-UNDO.
        DEFINE VARIABLE iOffset     AS INTEGER           NO-UNDO.
        DEFINE VARIABLE lRetVal     AS LOGICAL           NO-UNDO.

        MESSAGE "Entering getAdressenByWortIndex" VIEW-AS ALERT-BOX.

        iOffset = (iPage - 1) * iPageSize.

        EMPTY TEMP-TABLE ttAdresse.
        
        cWortIndex = ENTRY(1, cWortIndex, ' ').

        FOR EACH Adresse NO-LOCK
            WHERE INDEX(Adresse.WortIndex, cWortIndex) > 0
            AND Adresse.Firma = cCompanyID
            BY Adresse.Knr:
            CREATE ttAdresse.
            BUFFER-COPY Adresse TO ttAdresse.
        END.

        oJsonArray = NEW JsonArray().
        FOR EACH ttAdresse NO-LOCK:
            oJsonObject = NEW JsonObject().
            oJsonObject:Add("Knr", ttAdresse.Knr).
            oJsonObject:Add("Anzeig_br", ttAdresse.Anzeig_br).
            oJsonArray:Add(oJsonObject).
        END.

        oResponse = NEW OpenEdge.Web.WebResponse().
        oResponse:StatusCode = INTEGER(StatusCodeEnum:OK).
        oResponse:ContentType = "application/json;charset=utf-8".

        DEFINE VARIABLE lcString AS LONGCHAR NO-UNDO.
        oJsonArray:WRITE(lcString, FALSE).
        lcString = CHR(123) + ' "ttAdresse" : ' + lcString + CHR(125).

        COPY-LOB lcString TO FILE 'C:\TEMP\Json.txt'.

        oWriter = NEW WebResponseWriter(oResponse).
        oWriter:Open().
        /*    oWriter:Write(oJsonArray:ToString()).*/
        MESSAGE 'lcString Rückgabe: ' + STRING(lcString) VIEW-AS ALERT-BOX.        
        oWriter:Write(lcString).
        oWriter:Close().

        MESSAGE "Exiting getAdressenByWortIndex" VIEW-AS ALERT-BOX.

        RETURN 0.
    END METHOD.

    /* Methode zum Entfernen von Teilen des Strings außerhalb der eckigen Klammern */
    METHOD PUBLIC CHARACTER TrimBracketsFromLongChar(INPUT inputLongChar AS LONGCHAR):
        DEFINE VARIABLE startPosition AS INTEGER   NO-UNDO.
        DEFINE VARIABLE endPosition   AS INTEGER   NO-UNDO.
        DEFINE VARIABLE resultString  AS CHARACTER NO-UNDO.
        DEFINE VARIABLE inputString   AS CHARACTER NO-UNDO.

        /* Konvertiere LONGCHAR zu CHARACTER, da INDEX und R-INDEX mit CHARACTER arbeiten */
        inputString = STRING(inputLongChar).

        /* Finde die Position des ersten "[" */
        startPosition = INDEX(inputString, "[").

        /* Finde die Position des letzten "]" */
        endPosition = R-INDEX(inputString, "]").

        /* Überprüfe, ob beide Klammern gefunden wurden */
        IF startPosition > 0 AND endPosition > 0 AND endPosition > startPosition THEN 
        DO:
            /* Extrahiere den String zwischen den Klammern */
            resultString = SUBSTRING(inputString, startPosition + 1, endPosition - startPosition - 1).
        END.
        ELSE 
        DO:
            /* Wenn keine oder nur eine Klammer gefunden wurde, gib den ursprünglichen String zurück */
            resultString = inputString.
        END.

        RETURN resultString.
    END METHOD.

    METHOD OVERRIDE PROTECTED INTEGER HandleNotAllowedMethod(INPUT poRequest AS IWebRequest):
        DEFINE VARIABLE result AS INTEGER NO-UNDO.
        MESSAGE "HandleNotAllowedMethod called" VIEW-AS ALERT-BOX.
        RETURN result.
    END METHOD.

    METHOD OVERRIDE PROTECTED INTEGER HandleNotImplemented(INPUT poRequest AS IWebRequest):
        DEFINE VARIABLE result AS INTEGER NO-UNDO.
        MESSAGE "HandleNotImplemented called" VIEW-AS ALERT-BOX.
        RETURN result.
    END METHOD.

END CLASS.
