/*------------------------------------------------------------------------
   File        : programgeneratorImpl
   Purpose     : 
   Syntax      : 
   Description : 
   Author(s)   : walter.riechsteiner
   Created     : Wed Nov 19 13:23:38 CET 2025
   Notes       : 
 ----------------------------------------------------------------------*/


BLOCK-LEVEL ON ERROR UNDO, THROW.

USING OpenEdge.Core.String FROM PROPATH.
USING OpenEdge.Net.HTTP.IHttpResponse FROM PROPATH.
USING OpenEdge.Net.HTTP.StatusCodeEnum FROM PROPATH.
USING OpenEdge.Web.IWebRequest FROM PROPATH.
USING OpenEdge.Web.WebResponseWriter FROM PROPATH.
USING Progress.Json.ObjectModel.ObjectModelParser FROM PROPATH.
USING Progress.Json.ObjectModel.JsonObject FROM PROPATH.
USING Progress.Json.ObjectModel.JsonArray FROM PROPATH.
USING src.ch.adprime.gemis.WebHandlerUtilities FROM PROPATH.
USING utilities.utilitiesHandler FROM PROPATH.
USING utilities.selectboxHandler FROM PROPATH.
USING OpenEdge.Web.WebHandler FROM PROPATH.

CLASS admin.programgeneratorImpl INHERITS WebHandler: 

    DEFINE VARIABLE ccompany          AS CHARACTER        NO-UNDO.
    DEFINE VARIABLE cuser_name        AS CHARACTER        NO-UNDO.
    DEFINE VARIABLE cAnzeigeName      AS CHARACTER        NO-UNDO.
    DEFINE VARIABLE ilanguage_id      AS INTEGER          NO-UNDO.
    DEFINE VARIABLE cSessionToken     AS CHARACTER        NO-UNDO.
    
    DEFINE VARIABLE outilitiesHandler AS utilitiesHandler NO-UNDO.


    /*------------------------------------------------------------------------------
     Purpose:
     Notes:
    ------------------------------------------------------------------------------*/

    METHOD OVERRIDE PROTECTED INTEGER HandleGet (INPUT poRequest AS IWebRequest ):
        DEFINE VARIABLE oResponse       AS IHttpResponse     NO-UNDO.         
        DEFINE VARIABLE oWriter         AS WebResponseWriter NO-UNDO.
        DEFINE VARIABLE oBody           AS String            NO-UNDO.
        DEFINE VARIABLE cDefautlCharSet AS CHARACTER         NO-UNDO INIT 'UTF-8'.
        DEFINE VARIABLE oParser         AS ObjectModelParser NO-UNDO.           
        DEFINE VARIABLE cCorralationID  AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cContent-Type   AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE lcJsonInhalt    AS LONGCHAR          NO-UNDO.
        
        DEFINE VARIABLE oJsonResponse   AS JsonObject        NO-UNDO.
        DEFINE VARIABLE oJsonIdent      AS JsonObject        NO-UNDO.
        
        DEFINE VARIABLE ccompany        AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cuser_name      AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE ilanguage_id    AS INTEGER           NO-UNDO.
        DEFINE VARIABLE cFunction       AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cForm_Id        AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cProgram        AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE lRetVal         AS LOGICAL           NO-UNDO.
        DEFINE VARIABLE ii              AS INTEGER           NO-UNDO.
        DEFINE VARIABLE i1              AS INTEGER           NO-UNDO.
        DEFINE VARIABLE cQueryString    AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cQueryPairs     AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cQueryKey       AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cQueryValue     AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cProgUser       AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE lcProgramCode   AS LONGCHAR          NO-UNDO.
        
        outilitiesHandler = NEW utilitiesHandler().
        
        cForm_Id = poRequest:URI:GetQueryValue("progname") NO-ERROR.
        
        outilitiesHandler:getHeaderData(
            INPUT  poRequest    ,
            OUTPUT ccompany     ,
            OUTPUT cuser_name   ,
            OUTPUT cAnzeigeName ,
            OUTPUT ilanguage_id ,
            OUTPUT cSessionToken
            ).
        
        oJsonIdent = NEW JsonObject().
        oJsonIdent:ADD('company'     , ccompany     ).
        oJsonIdent:ADD('user_name'   , cuser_name   ).
        oJsonIdent:ADD('language_id' , iLanguage_id ).
        oJsonIdent:ADD('sessionToken', cSessionToken).
        
        cQueryString = STRING(poRequest:GetContextValue("QUERY_STRING"))    NO-ERROR.
        DO ii = 1 TO NUM-ENTRIES(cQueryString, '&'):
            cQueryPairs = ENTRY(ii, cQueryString, '&').
            cQueryKey   = ENTRY(1 , cQueryPairs , '=').
            cQueryValue = ENTRY(2 , cQueryPairs , '=').
            IF oJsonIdent:Has(cQueryKey) THEN oJsonIdent:SET(cQueryKey, cQueryValue) NO-ERROR.
            ELSE                              oJsonIdent:ADD(cQueryKey, cQueryValue) NO-ERROR.
        END.
        
        // MESSAGE 'oJsonIdent = ' STRING(oJsonIdent:write(lcJsonInhalt)).
        
        cFunction = oJsonIdent:GetCharacter('function') NO-ERROR.
        cProgram  = oJsonIdent:GetCharacter('program_name') NO-ERROR.
        
        cProgUser = cuser_name.
        lRetVal   = FALSE.
        // MESSAGE 'company = ' ccompany '- proguser = ' cproguser '- ilanguage_id = ' iLanguage_id '- program = ' cprogram. 
        DO WHILE TRUE:
            FIND FIRST htmldokumente NO-LOCK 
                WHERE htmldokumente.company     = ccompany
                AND   htmldokumente.user_name   = cProgUser
                AND   htmldokumente.language_id = iLanguage_id
                AND   htmldokumente.program     = cProgram NO-ERROR.
            
            IF NOT AVAILABLE htmldokumente THEN 
            DO:
                IF cProgUser = 'admin' THEN LEAVE.
                cProgUser = 'admin'.
                NEXT.
            END.
            MESSAGE 'gefunden mit user ' cproguser.
            COPY-LOB htmldokumente.htmlprogram TO lcProgramCode.
            /*            lcProgramCode = REPLACE(lcProgramCode, '"'    , '\"').*/
            /*            lcProgramCode = REPLACE(lcProgramCode, CHR(13), '\r').*/
            /*            lcProgramCode = REPLACE(lcProgramCode, CHR(10), '\n').*/
            /*            lcProgramCode = REPLACE(lcProgramCode, CHR(09), '\t').*/
            
            lRetVal = TRUE.
            LEAVE.
        END.
        
        // MESSAGE 'oJsonIdent = ' STRING(oJsonIdent:GetJsonText()).

        oJsonResponse = NEW JsonObject().
        oJsonResponse:ADD('program_name', cProgram).
        oJsonResponse:ADD('form_id'     , cProgram).
        oJsonResponse:ADD('program_code', lcprogramcode).
        oJsonResponse:ADD('created_at'  , ISO-DATE(htmldokumente.created_at)).
        /*        oJsonResponse:ADD('program_code', lcprogramcode).*/
        
        // oJsonResponse:WriteFile('C:\Temp\programmgenerator.json').
        oJsonResponse:WRITE(lcJsonInhalt, FALSE).

        IF NOT lRetVal THEN 
        DO:
            oJsonResponse = NEW JsonObject().
            oJsonResponse:ADD('success', FALSE).
            oJsonResponse:WRITE(lcJsonInhalt, FALSE).
        END.
                
        cContent-Type   = "application/json".
        cDefautlCharSet = 'utf-8'.

        oBody = NEW STRING(lcJsonInhalt).
        WebHandlerUtilities:createHttpResponse(INPUT INTEGER(StatusCodeEnum:OK), INPUT oBody, INPUT cContent-Type, INPUT cDefautlCharSet, INPUT cCorralationID, OUTPUT oResponse).
//        oResponse:SetHeader(HttpHeaderBuilder:Build(cHeaderCorralationID):Value(cCorralationID):Header).

        
        oWriter = NEW WebResponseWriter(oResponse).
        oWriter:Open(). 
        oWriter:Close(). 

        RETURN 0.
        
        CATCH e AS Progress.Lang.Error:

        END CATCH.

        FINALLY:

        END FINALLY.

    END METHOD.

    /*------------------------------------------------------------------------------
     Purpose:
     Notes:
    ------------------------------------------------------------------------------*/

    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 oJsonMessage      AS JsonObject        NO-UNDO.
        DEFINE VARIABLE oJsonResponse     AS JsonObject        NO-UNDO.
        DEFINE VARIABLE oParser           AS ObjectModelParser NO-UNDO.
        DEFINE VARIABLE oJsonIdent        AS JsonObject        NO-UNDO.           
        
        DEFINE VARIABLE lRetVal           AS LOGICAL           NO-UNDO.
        DEFINE VARIABLE lcJsonString      AS LONGCHAR          NO-UNDO.
        DEFINE VARIABLE cJSON             AS LONGCHAR          NO-UNDO.
        DEFINE VARIABLE i1                AS INTEGER           NO-UNDO.
        
        DEFINE VARIABLE ccompany          AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cuser_name        AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE ilanguage_id      AS INTEGER           NO-UNDO.
        DEFINE VARIABLE cProgram          AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cFormId           AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cFunction         AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cTargetUser       AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE iTargetLanguageId AS INTEGER           NO-UNDO.
        DEFINE VARIABLE cTargetCompany    AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cNames            AS CHARACTER         NO-UNDO EXTENT.
        DEFINE VARIABLE cName             AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE lcBase64_code     AS LONGCHAR          NO-UNDO.
        DEFINE VARIABLE lcProgramCode     AS LONGCHAR          NO-UNDO.
        DEFINE VARIABLE mDecodedCode      AS MEMPTR            NO-UNDO.
        
        lRetVal = WebHandlerUtilities:getJsonFromRequest(INPUT poRequest, OUTPUT oJsonData) NO-ERROR.
        
        IF oJsonData:has('program_code_base64') THEN 
        DO:
            lcBase64_code = oJsonData:GetLongchar("program_code_base64").
            mDecodedCode  = BASE64-DECODE(lcBase64_code).
            IF GET-SIZE(mDecodedCode) > 0 THEN 
            DO:
                COPY-LOB FROM mDecodedCode TO lcProgramCode CONVERT TARGET CODEPAGE "UTF-8".
                oJsonData:Remove('program_code_base64').
            END.
        END.
        IF oJsonData:has('program_code') THEN 
        DO:
            lcProgramcode = oJsonData:GetLongchar("program_code4").
            oJsonData:Remove('program_code_base64').
        END.
        
            
        outilitiesHandler = NEW utilitiesHandler().
        
        outilitiesHandler:getHeaderData(
            INPUT  poRequest    ,
            OUTPUT ccompany     ,
            OUTPUT cuser_name   ,
            OUTPUT cAnzeigeName ,
            OUTPUT ilanguage_id ,
            OUTPUT cSessionToken
            ).

        cFunction         =         oJsonData:GetCharacter('function').        
        cProgram          =         oJsonData:GetCharacter('program_name').        
        cFormId           =         oJsonData:GetCharacter('form_id').        
        cTargetUser       =         oJsonData:GetCharacter('target_user').        
        iTargetLanguageId = INTEGER(oJsonData:GetCharacter('target_language_id')).
        cTargetCompany    =         oJsonData:GetCharacter('target_company' ).

        lRetVal = FALSE.
        REPEAT TRANSACTION WHILE cFunction = 'save' ON ERROR UNDO, LEAVE:
            FIND htmldokumente  
                WHERE htmldokumente.company     = cTargetCompany
                AND   htmldokumente.user_name   = cTargetUser
                AND   htmldokumente.form_id     = cFormId
                AND   htmldokumente.language_id = iTargetLanguageId NO-ERROR.
            IF NOT AVAILABLE htmldokumente THEN LEAVE.
            
            ASSIGN
                htmldokumente.program = cProgram.
            COPY-LOB lcProgramCode TO htmldokumente.htmlprogram.
            RELEASE htmldokumente.
            
            lRetVal = TRUE.    
            LEAVE.
        END.
                    
        oResponse             = NEW OpenEdge.Web.WebResponse().
        oResponse:StatusCode  = INTEGER(StatusCodeEnum:OK).
        oResponse:ContentType = "application/json;charset=utf-8".
        oWriter               = NEW WebResponseWriter(oResponse).
                        
        oJsonMessage = NEW JsonObject().
        IF lRetVal THEN 
        DO:
            oJsonMessage:ADD('success', TRUE).
            oJsonMessage:WRITE(lcJsonString, TRUE).
        END.
        ELSE 
        DO:
            oJsonMessage:ADD('success', TRUE).
            oJsonMessage:ADD('message', 'Fehler beim erstellen der Menu-Struktur').
            oJsonMessage:WRITE(lcJsonString, FALSE).
        END.
        // MESSAGE 'Rückmeldung ' STRING(lcJsonString).
                            
        oWriter:Open().
        oWriter:Write(lcJsonString).
        oWriter:Close().
    
        RETURN 0.
    
        CATCH e AS Progress.Lang.Error:
                
        END CATCH.
                
        FINALLY:
        /*            DELETE OBJECT oJsonConfig. */
        /*            DELETE OBJECT oJsonMessage.*/
        END FINALLY.

    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.

    DESTRUCTOR PUBLIC programgeneratorImpl ( ):

    END DESTRUCTOR.

END CLASS.