/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.engine.util;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.codahale.metrics.Counting;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Metered;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;

/**
 * Periodically produces an update on a pipeline's progress
 *
 * Updates are provided at {@link #UPDATE_INTERVAL} in milliseconds.
 */
public abstract class ProgressNotifier {

  public static final long INITIAL_DELAY = 200;
  public static final long UPDATE_INTERVAL = 100;

  /**
   * A {@link TimerTask} to periodically update the user with whats going on in a pipeline.
   */
  private class Updater implements Runnable {

    @Override
    public void run() {
      updateStatus();
    }
  }

  /**
   * Does the work of updating the current status
   */
  protected abstract void updateStatus();

  /**
   * The {@link MetricRegistry} that progress is obtained from.
   */
  private final MetricRegistry metrics;

  private final ScheduledExecutorService executor;

  public ProgressNotifier(MetricRegistry metrics, long initialDelayMs, long updateIntervalMs) {
    this.metrics = metrics;
    this.executor = new ScheduledThreadPoolExecutor(1, runnable -> new Thread(runnable, "PipelineProgressMonitor"));
    this.executor.scheduleAtFixedRate(new Updater(), initialDelayMs, updateIntervalMs, TimeUnit.MILLISECONDS);
  }

  public ProgressNotifier(MetricRegistry metrics) {
    this(metrics, INITIAL_DELAY, UPDATE_INTERVAL);
  }

  protected List<String> buildUpdateMessage() {
    List<String> statusLines = new ArrayList<>();

    // report PercentGauges first, as they are used to indicate overall percentage progress
    for (String metricName: metrics.getNames()) {
      Metric metric = metrics.getMetrics().get(metricName);
      if (metric instanceof PercentGauge) {
        PercentGauge gauge = (PercentGauge) metric;
        if (gauge.hasValue()) {
          statusLines.add(String.format("%8d / %8d     %6.2f%%  %s",
              gauge.getNumerator(), gauge.getDenominator(), gauge.getValue(), metricName));
        }
      }
    }

    for (String metricName: metrics.getNames()) {
      Metric metric = metrics.getMetrics().get(metricName);
      // we keep things simple for the user by only outputting tuple counts. but these counts can
      // come from other metric types like timer or meter.
      if (metric instanceof Counting) {
        Counting count = (Counting)metric;
        if (count.getCount() == 0) {
          // If a count is 0 then we can ignore it, as the part of the job has yet to kick off.
          continue;
        }
        String toPrint = String.format("%2$31d: %1$s", metricName, count.getCount());
        if (metric instanceof Metered) {
          Metered meter = (Metered) metric;
          toPrint = String.format("%2$8d total, %3$9.3f/s avg: %1$5s",
              metricName, meter.getCount(), meter.getOneMinuteRate());
        }
        statusLines.add(toPrint);
      }
    }

    // print out gauges separately
    for (String metricName: metrics.getNames()) {
      Metric metric = metrics.getMetrics().get(metricName);
      if (metric instanceof PercentGauge) {
        continue;
      }

      if (metric instanceof Gauge<?> gauge) {
        statusLines.add(String.format("%2$31s: %1s", metricName, gauge.getValue()));
      }
    }

    return statusLines;
  }

  public void finish() {
    executor.shutdown();
    try {
      // Now we wait just in case a status update is in flight. If we didn't wait you can get some
      // junk output on the terminal if a status update is in flight during the terminal shutdown.
      executor.awaitTermination(500, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {}
  }

}
