/*------------------------------------------------------------------------
   File        : webhookImpl
   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 utilities.webhookHandler FROM PROPATH.
USING src.ch.adprime.gemis.WebHandlerUtilities FROM PROPATH.

CLASS webhookImpl INHERITS WebHandler:
    
    DEFINE VARIABLE cAktion         AS CHARACTER      NO-UNDO.
    
    DEFINE VARIABLE owebhookHandler AS webhookHandler.
    
    { ttWebhook.i  }
    { ttSendMail.i }

    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 lcJsonString AS LONGCHAR          NO-UNDO.
        
        DEFINE VARIABLE lRetVal      AS LOGICAL           NO-UNDO.
        
        DEFINE VARIABLE hbttMandant  AS HANDLE            NO-UNDO.
        DEFINE VARIABLE cGetHtml     AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE lcHTML       AS LONGCHAR          NO-UNDO.
        DEFINE VARIABLE cDatei       AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE ii           AS INTEGER           NO-UNDO.
        DEFINE VARIABLE i1           AS INTEGER           NO-UNDO.
        DEFINE VARIABLE iMaxParam    AS INTEGER           NO-UNDO.
        DEFINE VARIABLE lAdmin       AS LOGICAL           NO-UNDO.
        DEFINE VARIABLE oInput       AS JsonObject        NO-UNDO.
        DEFINE VARIABLE cMeldung     AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE lcString     AS LONGCHAR          NO-UNDO.
        DEFINE VARIABLE cString      AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cDevices     AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE cReplace     AS CHARACTER         NO-UNDO.
        DEFINE VARIABLE lOK          AS LOGICAL           NO-UNDO.
        DEFINE VARIABLE cParameter   AS CHARACTER         NO-UNDO EXTENT 20.

        MESSAGE "Entering HandlePost" VIEW-AS ALERT-BOX.
        
        lRetVal = WebHandlerUtilities:getJsonFromRequest(INPUT poRequest, OUTPUT oJsonData) NO-ERROR.
        oJsonData:WRITE(lcJsonString, FALSE).
        //
        //  Input-Daten aus JsonObject lesen und in ttWebhook füllen
        //
        EMPTY TEMP-TABLE ttWebhook.
        hbttWebhook = TEMP-TABLE ttWebhook:DEFAULT-BUFFER-HANDLE.
        oInput    = NEW JsonObject().
        oInput    = oJsonData:GetJsonObject('ttWebhook').
        lRetVal   = hbttWebhook:READ-JSON ('JsonObject', oInput).
        
        FIND FIRST ttWebhook.
        cAktion = ttWebhook.caction.
        
        owebhookHandler = NEW webhookHandler().

        DO WHILE lRetVal:
            hbttWebhook = TEMP-TABLE ttWebhook:DEFAULT-BUFFER-HANDLE.
            
            MESSAGE 'Inputdaten gelesen mit returncode ' lRetVal.
            IF NOT lRetVal THEN LEAVE.
            
            FIND FIRST ttWebhook.
             
            EMPTY TEMP-TABLE ttSendMail.
            CREATE  ttSendMail.
            ASSIGN
                ttSendMail.cFrom         = cMailFrom
                ttSendMail.cTo           = (IF ttWebhook.cTo = '' THEN 'info@analytikdataprime.ch' ELSE ttWebhook.cTo)
                ttSendMail.cAuthUsername = cAuthUserName
                ttSendMail.cAuthPasswort = cAuthPasswort
                ttSendMail.cCC           = (IF ttWebhook.cCc = '' THEN '' ELSE ttWebhook.cCc)
                ttSendMail.cBC           = (IF ttWebhook.cBc = '' THEN '' ELSE ttWebhook.cBc)
                ttSendMail.cSubject      = ttWebhook.cSubject 
                ttSendMail.cBody         = ttWebHook.cBody
                ttSendMail.cMailServer   = cMailServer
                ttSendMail.cMailPort     = cMailPort
                ttSendMail.cDomaine      = cMailDomaine
                ttSendMail.lMailAuth     = lMailAuth
                ttSendMail.cMailKonto    = cMailKonto
                ttSendMail.cMailPassw    = cMailPassw
                ttSendMail.lSSLEnabled   = lSSLEnable
                .
            cParameter = ''.
            iMaxParam  = NUM-ENTRIES(ttWebhook.cbody, ';').
            DO ii = 1 TO iMaxParam:
                cParameter[ii] = TRIM(ENTRY(ii, ttWebhook.cbody, ';')).
            END.
                
            IF ttWebhook.caction = 'SYNOLOGY' THEN 
            DO:
                oJsonData:WRITE(lcJsonString, FALSE).
                
                FIND FIRST ttWebhook.
                IF INDEX(ttWebhook.cHerkunft, 'M365') > 0 THEN 
                DO:
                    //  Parameter  1:   Anzahl OneDrive Ordner
                    //  Parameter  2:   Anzahl E-Mail Postfächer
                    //  Parameter  3:   Anzahl Archive Postfäher
                    //  Parameter  4:   Anzahl Kontakte
                    //  Parameter  5:   Anzahl Kalender
                    //  Parameter  6:   Anzahl Share-Point - Verzeichnisse
                    //  Parameter  7:   Anzahl Gruppen-E-Mail Postfächer
                    //  Parameter  8:   Anzahl Gruppenkalender
                    //  Parameter  9:   Anzahl Teams
                    //  Parameter 10:   Startzeit
                    //  Parameter 11:   Endzeit
                    //  Parameter 12:   Host (ADPRNAS01, ...)
                    //  Parameter 13:   Taskname
                    //  Parameter 14:   Texte aus Aufgaben-Regel
                    DO:
                        IF ttWebhook.cmeldungsart = 'success' THEN cDatei = SEARCH('M365_Success_Text.txt').
                        IF ttWebhook.cmeldungsart = 'error'   THEN cDatei = SEARCH('M365_Error_Text.txt').
                        IF ttWebhook.cmeldungsart = 'fehler'  THEN cDatei = SEARCH('M365_Error_Text.txt').
                        IF ttWebhook.cmeldungsart = 'warning' THEN cDatei = SEARCH('M365_Warning_Text.txt').
                        COPY-LOB FROM FILE cDatei TO lcString.
                        lcString = REPLACE(lcString, CHR(13), '').
                        lcString = REPLACE(lcString, CHR(10), '</br>').
                    END.
                    
                    CASE ttWebhook.cmeldungsart:
                        WHEN 'success' THEN
                            DO:
                                DO ii = 1 TO iMaxParam:
                                    cReplace = '&' + STRING(ii,"99").
                                    lcString = REPLACE(lcString, cReplace, cParameter[ii]).
                                END.
                                ASSIGN
                                    ttSendMail.cSubject = SUBSTITUTE('&1 / &2', cParameter[12], cParameter[13])
                                    ttSendMail.cBody    = ttWebhook.cHerkunft + '</br></br>' + STRING(lcString).
                            END.
                        WHEN 'fehler' OR
                        WHEN 'error'  THEN
                            DO:
                                DO ii = 1 TO iMaxParam:
                                    cReplace = '&' + STRING(ii,"99").
                                    lcString = REPLACE(lcString, cReplace, cParameter[ii]).
                                END.
                                ASSIGN
                                    ttSendMail.cSubject = SUBSTITUTE('&1 / &2', cParameter[12], cParameter[13])
                                    ttSendMail.cBody    = ttWebhook.cHerkunft + '</br></br>' + STRING(lcString).
                            END.
                        OTHERWISE 
                        DO:
                            ASSIGN 
                                ttSendMail.cSubject = SUBSTITUTE('&1 / &2', cParameter[12], cParameter[13])
                                ttSendMail.cBody    = ttWebhook.cHerkunft + '</br></br>' + ttWebhook.cbody.
                        END.
                    END CASE.
                END.
                
                IF INDEX(ttWebhook.cHerkunft, 'Business') > 0 THEN 
                DO:
                    //  Parameter  1:   Startzeit
                    //  Parameter  2:   Endzeit
                    //  Parameter  3:   Grösse transferierter Daten
                    //  Parameter  4:   Geräte
                    //  Parameter  5:   Host (ADPRNAS01, ...)
                    //  Parameter  6:   Taskname
                    //  Parameter  7:   Texte aus Aufgaben-Regel
                    DO:
                        cDatei = SEARCH('VM_Success_Text.txt').
                        IF ttWebhook.cmeldungsart = 'success' THEN cDatei = SEARCH('VM_Success_Text.txt').
                        IF ttWebhook.cmeldungsart = 'error'   THEN cDatei = SEARCH('VM_Error_Text.txt').
                        IF ttWebhook.cmeldungsart = 'fehler'  THEN cDatei = SEARCH('VM_Error_Text.txt').
                        IF ttWebhook.cmeldungsart = 'warning' THEN cDatei = SEARCH('VM_Warning_Text.txt').
                        IF ttWebhook.cmeldungsart = 'warnung' THEN cDatei = SEARCH('VM_Warning_Text.txt').
                        COPY-LOB FROM FILE cDatei TO lcString.
                        lcString = REPLACE(lcString, CHR(13), '').
                        lcString = REPLACE(lcString, CHR(10), '</br>').
                    END.
                    
                    cDevices = ''.
                    cString  = cParameter[04].
                    cString  = REPLACE(cString, ',', '').
                    DO ii = 1 TO NUM-ENTRIES(cString, ' '):
                        cDevices = cDevices + '</br>  - ' + entry(ii, cString, ' ').
                    END.
                    cParameter[04] = cDevices.
                    CASE ttWebhook.cmeldungsart:
                        WHEN 'success' THEN 
                            DO:
                                DO ii = 1 TO iMaxParam:
                                    cReplace = '&' + STRING(ii,"99").
                                    lcString = REPLACE(lcString, cReplace, cParameter[ii]).
                                END.
                                ASSIGN
                                    ttSendMail.cSubject = SUBSTITUTE('&1 / &2', cParameter[05], cParameter[06])
                                    ttSendMail.cBody    = ttWebhook.cHerkunft + '</br></br>' + STRING(lcString).
                            END.
                        WHEN 'fehler' OR
                        WHEN 'error'  THEN 
                            DO:
                                DO ii = 1 TO iMaxParam:
                                    cReplace = '&' + STRING(ii,"99").
                                    lcString = REPLACE(lcString, cReplace, cParameter[ii]).
                                END.
                                ASSIGN
                                    ttSendMail.cSubject = SUBSTITUTE('&1 / &2', cParameter[05], cParameter[06])
                                    ttSendMail.cBody    = ttWebhook.cHerkunft + '</br></br>' + STRING(lcString).
                            END.
                        WHEN 'warnung' OR
                        WHEN 'warning' THEN 
                            DO:
                                DO ii = 1 TO iMaxParam:
                                    cReplace = '&' + STRING(ii,"99").
                                    lcString = REPLACE(lcString, cReplace, cParameter[ii]).
                                END.
                                ASSIGN
                                    ttSendMail.cSubject = SUBSTITUTE('&1 / &2', cParameter[05], cParameter[06])
                                    ttSendMail.cBody    = ttWebhook.cHerkunft + '</br></br>' + STRING(lcString).
                            END.
                        OTHERWISE 
                        DO:
                            ASSIGN 
                                ttSendMail.cSubject = SUBSTITUTE('&1 / &2', cParameter[05], cParameter[06])
                                ttSendMail.cBody    = ttWebhook.cHerkunft + '</br></br>' + ttWebhook.cbody.
                        END.
                    END CASE.
                END.
                
                /*                ASSIGN                                                                      */
                /*                    ttSendMail.cBody = ttWebhook.cHerkunft + '</br></br>' + ttWebhook.cBody.*/
                
                lcJsonString = ''.
                DO ii = 1 TO hbttWebhook:NUM-FIELDS:
                    lcJsonString = lcJsonString
                        + (IF lcJsonString = '' THEN '' ELSE ', ')
                        + QUOTER(hbttWebhook:BUFFER-FIELD(ii):NAME) 
                        + ': '
                        + QUOTER(hbttWebhook:BUFFER-FIELD(ii):BUFFER-VALUE).
                END.
                lcJsonString = CHR(123) + lcJsonString + chr(125).
                MESSAGE 'Return-Daten nach füllen aus ttWebhook ' STRING(lcJsonString).
                
                httSendMail = TEMP-TABLE ttSendMail:DEFAULT-BUFFER-HANDLE.
                RUN sendsmtpmail.r ( INPUT httSendMail, OUTPUT cMeldung, OUTPUT lOK ).
                MESSAGE 'Meldung beim Versand von Mail: ' lOk '-' cMeldung.
            END.
            LEAVE.
        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 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.
