package com.airlock.iam.application.webserver.infrastructure.health;

import com.google.common.annotations.VisibleForTesting;
import java.lang.management.ManagementFactory;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.HealthCheckResponseBuilder;

public final class LogForwarderCheck implements HealthCheck {
   static final String STATUS_OBJECT_NAME = "com.airlock.iam:type=LogForwarderStatus";
   private static final String CHECK_NAME = "logforwarder";
   private final MBeanServer mBeanServer;

   public LogForwarderCheck() {
      this(ManagementFactory.getPlatformMBeanServer());
   }

   @VisibleForTesting
   LogForwarderCheck(MBeanServer mBeanServer) {
      this.mBeanServer = mBeanServer;
   }

   public HealthCheckResponse call() {
      HealthCheckResponseBuilder response = HealthCheckResponse.named("logforwarder");

      try {
         String status = (String)this.mBeanServer.getAttribute(new ObjectName("com.airlock.iam:type=LogForwarderStatus"), "Status");
         response.status("UP".equals(status));
      } catch (JMException e) {
         response.down();
      }

      return response.build();
   }
}
