package com.konkerlabs.platform.registry.audit;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.konkerlabs.platform.registry.audit.repositories.TenantLogRepository;
import com.konkerlabs.platform.registry.business.model.enumerations.LogLevel;
import org.slf4j.MDC;

import java.net.URI;
import java.sql.Date;
import java.time.Instant;


public class KonkerLoggerAppender extends AppenderBase<ILoggingEvent> {

    public static final String CONTEXT = "context";

    private TenantLogRepository repository;

    public KonkerLoggerAppender(TenantLogRepository repository) {
        this.repository = repository;
    }

    public KonkerLoggerAppender() {}



    @Override
    public void start() {
        super.start();
        if(repository == null){
            try {
                repository = TenantLogRepository.getInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    @Override
    public void doAppend(ILoggingEvent eventObject) {
        super.doAppend(eventObject);
    }

    @Override
    public void append(ILoggingEvent iLoggingEvent) {
        enrich(iLoggingEvent);
    }


    /**
     * Enrich log with tenant info
     * @param eventObject
     */
    private void enrich(ILoggingEvent eventObject) {

        if (eventObject != null && eventObject instanceof LoggingEvent) {
            if (eventObject.getArgumentArray() != null
                    && eventObject.getArgumentArray().length > 1 ){
                URI uri = null;
                LogLevel logLevel = null;
                for(Object item : eventObject.getArgumentArray()){
                    if (item instanceof URI && !((URI) item).getScheme().equals("http")) {
                        uri = (URI) item;
                    }
                    if(item instanceof LogLevel){
                        logLevel = (LogLevel) item;
                    }
                }
                if(uri != null && logLevel != null && logLevel.getId().equals(eventObject.getLevel().levelStr)){
                    MDC.put(CONTEXT, encodeDealer(uri));
                    store(eventObject, getTenant(uri), eventObject.getFormattedMessage());
                }
            }

        }
    }

    /**
     * Store log into datastore
     * @param event
     * @param tenantDomain
     * @param trace
     */
    public void store(ILoggingEvent event, String tenantDomain, String trace) {
        repository.insert(tenantDomain, Date.from(Instant.ofEpochMilli(event.getTimeStamp())), trace);
    }

    /**
     * Encode URIDealer to log format
     *
     * @param dealer
     * @return String  - entity: {val}, tentant: {val}, guid: {val}
     */
    private String encodeDealer(URI dealer) {
        return "Entity: " + dealer.getScheme() + ", Tenant: "
                + dealer.getHost() + ", Guid: " + dealer.getPath().replaceAll("/", "");
    }

    /**
     * Return tentant info
     * @param dealer
     * @return tentantDomain
     */
    private String getTenant(URI dealer) {
        return dealer.getHost();
    }

    /**
     * Return schema
     * @param dealer
     * @return entityName
     */
    private String getEntity(URI dealer) {
        return dealer.getScheme();
    }

    public void setRepository(TenantLogRepository repository) {
        this.repository = repository;
    }
}

@@ -42,16 +42,53 @@
 audit;%0A%0A
+import ch.qos.logback.classic.Level;%0A
 import c
@@ -120,32 +120,32 @@
 .ILoggingEvent;%0A
-
 import ch.qos.lo
@@ -396,16 +396,61 @@
 f4j.MDC;
+%0Aimport org.springframework.util.StringUtils;
 %0A%0Aimport
@@ -831,18 +831,22 @@
 nder() %7B
-%7D
 %0A
+    %7D
 %0A%0A%0A    @
@@ -913,16 +913,17 @@
       if
+ 
 (reposit
@@ -934,16 +934,17 @@
 == null)
+ 
 %7B%0A      
@@ -1379,32 +1379,39 @@
 ith tenant info%0A
+     *%0A
      * @param ev
@@ -1679,10 +1679,10 @@
  %3E 1
- 
 )
+ 
 %7B%0A  
@@ -1772,16 +1772,17 @@
      for
+ 
 (Object 
@@ -1819,16 +1819,17 @@
 Array())
+ 
 %7B%0A      
@@ -1999,16 +1999,17 @@
       if
+ 
 (item in
@@ -2026,16 +2026,17 @@
 ogLevel)
+ 
 %7B%0A      
@@ -2139,16 +2139,17 @@
       if
+ 
 (uri != 
@@ -2156,91 +2156,396 @@
 null
- && logLevel != null && logLevel.getId().equals(eventObject.getLevel().l
+%0A                        && logLevel != null%0A                        && !StringUtils.isEmpty(logLevel.getId())%0A                        && eventObject.getLevel() != null) %7B%0A                    Level userLogLevel = Level.toLevel(logLevel.getId());%0A                    Level eventLogLevel = eventObject.getLevel();%0A                    if (eventLogLevel.isGreaterOrEqual(userLogL
 evel
-Str
 ))
+ 
 %7B%0A
+    
     
@@ -2593,24 +2593,28 @@
 aler(uri));%0A
+    
             
@@ -2688,24 +2688,46 @@
 Message());%0A
+                    %7D%0A
             
@@ -2804,16 +2804,23 @@
 tastore%0A
+     *%0A
      * @
@@ -3460,24 +3460,31 @@
 entant info%0A
+     *%0A
      * @para
@@ -3612,32 +3612,32 @@
 %0A    %7D%0A%0A    /**%0A
-
      * Return sc
@@ -3641,16 +3641,23 @@
  schema%0A
+     *%0A
      * @

fix log level