import axios from "axios";
import type { Node } from "~/classes/node/Node";
import type { Pod } from "~/classes/Pod";
import { Data } from "../chart/Dataset";
import dayjs from "dayjs";

export class MonitoredResource<T>
{
    constructor (
        public resource: T,
        public jobs: IndexCollection[]
    ) { }

    static getMonitorings(monitoringId: string, from: number, to: number, onSuccess: (monitoredPod: MonitoredResource<Pod>[]) => void)
    {
        axios.get<MonitoredResource<Pod>[]>(StringUtils.format("%s/monitorings/%s/jobs", ApiConfig.getHttpBase(), monitoringId), {
            params: {
                from: from,
                to: to
            }
        })
            .then(response => {
                onSuccess(response.data)
            });
    }

    static getNodeMonitorings(from: Date, to: Date, onSuccess: (monitoredPod: MonitoredResource<Node>[]) => void)
    {
        axios.get<MonitoredResource<Node>[]>(ApiConfig.getHttpBase() + '/monitorings/nodes/jobs', {
            params: {
                from: from,
                to: to
            }
        })
            .then(response => {
                onSuccess(response.data)
            });
    }

    static extractDataset(key: string, jobs: IndexCollection[]): Data[]
    {
        const data = [] as Data[];
        for (const job of jobs)
        {
            const metrics = job.metrics[key];
            if (metrics != null)
            {
                data.push(new Data(metrics.average, dayjs.utc(job.timestamp).local().toDate()));
            }
        }
        return data;
    }
}

export class IndexCollection
{
    constructor (
        public metrics: Record<string, Metric>,
        public timestamp: Date,
        public unix: number
    ) { }
}

export class Metric
{
    constructor (
        public count: number,
        public sum: number,
        public average: number
    ) { }
}