import { Singleton, Container, Scope, Inject } from "typescript-ioc";
import { K8SConfigCache } from "./K8SConfigCache"
import httpClient from './HttpClient'
import { OpResult, logger } from 'mslib'

@Singleton
export class PromeClient {

    @Inject
    private configCache: K8SConfigCache

    async queryVector(k8sId: string, promQL: string, params: any): Promise<OpResult<PromeData>> {
        const config = this.configCache.getClient(k8sId);
        if (!config.prmsUrl) {
            return OpResult.error('查询失败，当前集群未部署Prometheus')
        }

        const data = Object.assign({}, params)
        data.query = promQL
        return await this.query(config.prmsUrl + 'api/v1/query', data)
    }

    async queryRange(k8sId: string, promQL: string, params: any): Promise<OpResult<PromeData>> {
        const config = this.configCache.getClient(k8sId);
        if (!config.prmsUrl) {
            return OpResult.error('查询失败，当前集群未部署Prometheus')
        }
        const data = Object.assign({}, params)
        data.query = promQL
        return await this.query(config.prmsUrl + 'api/v1/query_range', data)
    }



    async query(apiUrl: string, data: any): Promise<OpResult<PromeData>> {
        logger.info('Query------------------->apiUrl:%s,data:%s', apiUrl, JSON.stringify(data))
        const response = await httpClient.get(apiUrl, data).catch(error => {
            return Promise.resolve(error.response);
        });
        if (response?.status !== 200) {
            return OpResult.error(`查询失败，Response[${response?.status}]`)
        }
        if (response.data.status !== 'success') {
            return OpResult.error(`查询失败，Response[${response.data.status}]`)
        }
        return OpResult.success('OK', response.data.data)
    }

}

export interface PromeRes {
    metric: any
    value: Array<any>
}

export interface PromeData {
    resultType: string
    result: Array<PromeRes>
}
