#pragma once

#include "debug/metrics/NetworkMetrics.hpp"
#include "debug/tools/MetricWidget.hpp"

#include <imgui.h>

namespace tw::dbg::tools {

/**
 * Panel over everything the client measured about its traffic.
 *
 * Traffic is shown as the total of each second, since that is the rate the
 * connection actually carried. Durations are shown as the average of each
 * second, with the range behind them.
 */
class NetworkStatsGui {
    MetricWidget m_response;
    MetricWidget m_update;
    MetricWidget m_bytes_in;
    MetricWidget m_bytes_out;
    MetricWidget m_messages_in;
    MetricWidget m_messages_out;

    MetricWidget m_rollbacks;
    MetricWidget m_correction_distance;
    MetricWidget m_ack_lag_frames;
    MetricWidget m_replayed_frames;

    int m_history_in_seconds = 30;

public:
    explicit NetworkStatsGui(const NetworkMetrics& metrics) :
        m_response("Response", "ms", metrics.response_ms(), metrics::MetricField::Avg),
        m_update("Network update", "ms", metrics.update_ms(), metrics::MetricField::Avg),
        m_bytes_in("Bytes in", "B/s", metrics.bytes_in(), metrics::MetricField::Sum),
        m_bytes_out("Bytes out", "B/s", metrics.bytes_out(), metrics::MetricField::Sum),
        m_messages_in("Messages in", "1/s", metrics.messages_in(), metrics::MetricField::Sum),
        m_messages_out("Messages out", "1/s", metrics.messages_out(), metrics::MetricField::Sum),
        m_rollbacks("Rollbacks", "1/s", metrics.rollbacks(), metrics::MetricField::Sum),
        m_correction_distance("Correction distance", "m", metrics.correction_distance(), metrics::MetricField::Avg),
        m_ack_lag_frames("Ack lag", "frames", metrics.ack_lag_frames(), metrics::MetricField::Avg),
        m_replayed_frames("Replayed frames", "frames", metrics.replayed_frames(), metrics::MetricField::Avg)
    { }

    void draw() {
        ImGui::Begin("Network Stats");

        ImGui::SliderInt("History", &m_history_in_seconds, 5, 300, "%d s");

        const size_t history = (size_t)m_history_in_seconds;

        m_response.draw(history);
        m_update.draw(history);
        m_bytes_in.draw(history);
        m_bytes_out.draw(history);
        m_messages_in.draw(history);
        m_messages_out.draw(history);

        ImGui::Separator();
        ImGui::TextUnformatted("Prediction");
        m_rollbacks.draw(history);
        m_correction_distance.draw(history);
        m_ack_lag_frames.draw(history);
        m_replayed_frames.draw(history);

        ImGui::End();
    }
};

}
