"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PodMetricContainerUsageReference = exports.PodMetricContainerReference = exports.PodMetricReference = exports.PodMetricsListReference = exports.PodMetricUsage = exports.PodMetric = exports.PodMetrics = exports.Metricsv1beta1Api = exports.KubeUtil = void 0;
var client_node_1 = require("@kubernetes/client-node");
var localVarRequest = require("request");
var defaultBasePath = 'https://localhost';
var KubeUtil = /** @class */ (function () {
    function KubeUtil() {
        this.CoreV1Api = null; // kc.makeApiClient(k8s.CoreV1Api);
        this.AppsV1Api = null; // kc.makeApiClient(k8s.AppsV1Api);
        this.ExtensionsV1beta1Api = null; // kc.makeApiClient(k8s.ExtensionsV1beta1Api);
        this.Metricsv1beta1Api = null;
        var k8s = require("@kubernetes/client-node");
        var kc = new k8s.KubeConfig();
        var success = false;
        try {
            kc.loadFromDefault();
            success = true;
        }
        catch (error) {
            console.error(error);
        }
        if (success == false) {
            try {
                kc.loadFromCluster();
                success = true;
            }
            catch (error) {
                console.error(error);
            }
        }
        this.CoreV1Api = kc.makeApiClient(k8s.CoreV1Api);
        this.AppsV1Api = kc.makeApiClient(k8s.AppsV1Api);
        this.ExtensionsV1beta1Api = kc.makeApiClient(k8s.ExtensionsV1beta1Api);
        this.Metricsv1beta1Api = kc.makeApiClient(Metricsv1beta1Api);
    }
    KubeUtil.instance = function () {
        if (this._instance == null) {
            this._instance = new KubeUtil();
        }
        return this._instance;
    };
    KubeUtil.prototype.GetStatefulSet = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var list, i, item;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.AppsV1Api.listNamespacedStatefulSet(namespace)];
                    case 1:
                        list = _a.sent();
                        for (i = 0; i < list.body.items.length; i++) {
                            item = list.body.items[i];
                            if (item.metadata.name == name)
                                return [2 /*return*/, item];
                        }
                        return [2 /*return*/, null];
                }
            });
        });
    };
    KubeUtil.prototype.GetService = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var list, i, item;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.CoreV1Api.listNamespacedService(namespace)];
                    case 1:
                        list = _a.sent();
                        for (i = 0; i < list.body.items.length; i++) {
                            item = list.body.items[i];
                            if (item.metadata.name == name)
                                return [2 /*return*/, item];
                        }
                        return [2 /*return*/, null];
                }
            });
        });
    };
    KubeUtil.prototype.GetPod = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var list, i, item;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.CoreV1Api.listNamespacedPod(namespace)];
                    case 1:
                        list = _a.sent();
                        for (i = 0; i < list.body.items.length; i++) {
                            item = list.body.items[i];
                            if (item.metadata.name == name)
                                return [2 /*return*/, item];
                        }
                        return [2 /*return*/, null];
                }
            });
        });
    };
    KubeUtil.prototype.GetReplicaset = function (namespace, labelskey, labelsvalue) {
        return __awaiter(this, void 0, void 0, function () {
            var list, i, item, value;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.AppsV1Api.listNamespacedReplicaSet(namespace)];
                    case 1:
                        list = _a.sent();
                        for (i = 0; i < list.body.items.length; i++) {
                            item = list.body.items[i];
                            if (item.metadata && item.metadata.labels) {
                                value = item.metadata.labels[labelskey];
                                if (value == labelsvalue)
                                    return [2 /*return*/, item];
                            }
                        }
                        return [2 /*return*/, null];
                }
            });
        });
    };
    KubeUtil.prototype.GetDeployment = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var list, i, item;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.AppsV1Api.listNamespacedDeployment(namespace)];
                    case 1:
                        list = _a.sent();
                        for (i = 0; i < list.body.items.length; i++) {
                            item = list.body.items[i];
                            if (item.metadata.name == name)
                                return [2 /*return*/, item];
                        }
                        return [2 /*return*/, null];
                }
            });
        });
    };
    KubeUtil.prototype.GetIngressV1beta1 = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var list, i, item;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.ExtensionsV1beta1Api.listNamespacedIngress(namespace)];
                    case 1:
                        list = _a.sent();
                        for (i = 0; i < list.body.items.length; i++) {
                            item = list.body.items[i];
                            if (item.metadata.name == name)
                                return [2 /*return*/, item];
                        }
                        return [2 /*return*/, null];
                }
            });
        });
    };
    KubeUtil.prototype.GetPodMetrics = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var list;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.Metricsv1beta1Api.GetPod(namespace, name)];
                    case 1:
                        list = _a.sent();
                        if (list.body.containers.length > 0) {
                            list.body.containers[0].usage.window = list.body.window;
                            return [2 /*return*/, list.body.containers[0].usage];
                        }
                        return [2 /*return*/, null];
                }
            });
        });
    };
    KubeUtil._instance = null;
    return KubeUtil;
}());
exports.KubeUtil = KubeUtil;
var Metricsv1beta1Api = /** @class */ (function () {
    function Metricsv1beta1Api(basePathOrUsername, password, basePath) {
        this._basePath = null;
        this.authentications = null;
        this._useQuerystring = null;
        this.defaultHeaders = null;
        this._basePath = defaultBasePath;
        this.authentications = {
            'default': new client_node_1.VoidAuth(),
            'BearerToken': new client_node_1.ApiKeyAuth('header', 'authorization'),
        };
        if (password) {
            if (basePath) {
                this.basePath = basePath;
            }
        }
        else {
            if (basePathOrUsername) {
                this.basePath = basePathOrUsername;
            }
        }
    }
    Object.defineProperty(Metricsv1beta1Api.prototype, "useQuerystring", {
        set: function (value) {
            this._useQuerystring = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Metricsv1beta1Api.prototype, "basePath", {
        get: function () {
            return this._basePath;
        },
        set: function (basePath) {
            this._basePath = basePath;
        },
        enumerable: false,
        configurable: true
    });
    Metricsv1beta1Api.prototype.setDefaultAuthentication = function (auth) {
        this.authentications.default = auth;
    };
    Metricsv1beta1Api.prototype.GetPods = function (namespace) {
        return __awaiter(this, void 0, void 0, function () {
            var localVarPath, localVarHeaderParams, localVarUseFormData, localVarQueryParameters, localVarRequestOptions;
            return __generator(this, function (_a) {
                localVarPath = this.basePath + '/apis/metrics.k8s.io/v1beta1/pods';
                if (namespace != null)
                    localVarPath = this.basePath + '/apis/metrics.k8s.io/v1beta1/namespaces/' + namespace + "/pods";
                localVarHeaderParams = Object.assign({}, this.defaultHeaders);
                localVarUseFormData = false;
                localVarQueryParameters = {};
                localVarRequestOptions = {
                    method: 'GET',
                    qs: localVarQueryParameters,
                    headers: localVarHeaderParams,
                    uri: localVarPath,
                    useQuerystring: this._useQuerystring,
                    json: true,
                };
                this.authentications.BearerToken.applyToRequest(localVarRequestOptions);
                this.authentications.default.applyToRequest(localVarRequestOptions);
                return [2 /*return*/, new Promise(function (resolve, reject) {
                        localVarRequest(localVarRequestOptions, function (error, response, body) {
                            if (error) {
                                reject(error);
                            }
                            else {
                                body = ObjectSerializer.deserialize(body, "PodMetricsList");
                                if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
                                    resolve({ response: response, body: body });
                                }
                                else {
                                    reject({ response: response, body: body });
                                }
                            }
                        });
                    })];
            });
        });
    };
    Metricsv1beta1Api.prototype.GetPod = function (namespace, pod) {
        return __awaiter(this, void 0, void 0, function () {
            var localVarPath, localVarHeaderParams, localVarUseFormData, localVarQueryParameters, localVarRequestOptions;
            return __generator(this, function (_a) {
                localVarPath = this.basePath + '/apis/metrics.k8s.io/v1beta1/namespaces/' + namespace + "/pods/" + pod;
                localVarHeaderParams = Object.assign({}, this.defaultHeaders);
                localVarUseFormData = false;
                localVarQueryParameters = {};
                localVarRequestOptions = {
                    method: 'GET',
                    qs: localVarQueryParameters,
                    headers: localVarHeaderParams,
                    uri: localVarPath,
                    useQuerystring: this._useQuerystring,
                    json: true,
                };
                this.authentications.BearerToken.applyToRequest(localVarRequestOptions);
                this.authentications.default.applyToRequest(localVarRequestOptions);
                return [2 /*return*/, new Promise(function (resolve, reject) {
                        localVarRequest(localVarRequestOptions, function (error, response, body) {
                            if (error) {
                                reject(error);
                            }
                            else {
                                body = ObjectSerializer.deserialize(body, "PodMetrics");
                                if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
                                    resolve({ response: response, body: body });
                                }
                                else {
                                    reject({ response: response, body: body });
                                }
                            }
                        });
                    })];
            });
        });
    };
    return Metricsv1beta1Api;
}());
exports.Metricsv1beta1Api = Metricsv1beta1Api;
var primitives = [
    "string",
    "boolean",
    "double",
    "integer",
    "long",
    "float",
    "number",
    "any"
];
var ObjectSerializer = /** @class */ (function () {
    function ObjectSerializer() {
    }
    ObjectSerializer.findCorrectType = function (data, expectedType) {
        if (data == undefined) {
            return expectedType;
        }
        else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) {
            return expectedType;
        }
        else if (expectedType === "Date") {
            return expectedType;
        }
        else {
            if (enumsMap[expectedType]) {
                return expectedType;
            }
            if (!typeMap[expectedType]) {
                return expectedType; // w/e we don't know the type
            }
            // Check the discriminator
            var discriminatorProperty = typeMap[expectedType].discriminator;
            if (discriminatorProperty == null) {
                return expectedType; // the type does not have a discriminator. use it.
            }
            else {
                if (data[discriminatorProperty]) {
                    return data[discriminatorProperty]; // use the type given in the discriminator
                }
                else {
                    return expectedType; // discriminator was not present (or an empty string)
                }
            }
        }
    };
    ObjectSerializer.serialize = function (data, type) {
        if (data == undefined) {
            return data;
        }
        else if (primitives.indexOf(type.toLowerCase()) !== -1) {
            return data;
        }
        else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
            var subType = type.replace("Array<", ""); // Array<Type> => Type>
            subType = subType.substring(0, subType.length - 1); // Type> => Type
            var transformedData = [];
            for (var index in data) {
                var date = data[index];
                transformedData.push(ObjectSerializer.serialize(date, subType));
            }
            return transformedData;
        }
        else if (type === "Date") {
            return data.toString();
        }
        else {
            if (enumsMap[type]) {
                return data;
            }
            if (!typeMap[type]) { // in case we dont know the type
                return data;
            }
            // get the map for the correct type.
            var attributeTypes = typeMap[type].getAttributeTypeMap();
            var instance = {};
            for (var index in attributeTypes) {
                var attributeType = attributeTypes[index];
                instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type);
            }
            return instance;
        }
    };
    ObjectSerializer.deserialize = function (data, type) {
        // polymorphism may change the actual type.
        type = ObjectSerializer.findCorrectType(data, type);
        if (data == undefined) {
            return data;
        }
        else if (primitives.indexOf(type.toLowerCase()) !== -1) {
            return data;
        }
        else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
            var subType = type.replace("Array<", ""); // Array<Type> => Type>
            subType = subType.substring(0, subType.length - 1); // Type> => Type
            var transformedData = [];
            for (var index in data) {
                var date = data[index];
                transformedData.push(ObjectSerializer.deserialize(date, subType));
            }
            return transformedData;
        }
        else if (type === "Date") {
            return new Date(data);
        }
        else {
            if (enumsMap[type]) { // is Enum
                return data;
            }
            if (!typeMap[type]) { // dont know the type
                return data;
            }
            var instance = new typeMap[type]();
            var attributeTypes = typeMap[type].getAttributeTypeMap();
            for (var index in attributeTypes) {
                var attributeType = attributeTypes[index];
                instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type);
            }
            return instance;
        }
    };
    return ObjectSerializer;
}());
var PodMetrics = /** @class */ (function () {
    function PodMetrics() {
    }
    return PodMetrics;
}());
exports.PodMetrics = PodMetrics;
var PodMetric = /** @class */ (function () {
    function PodMetric() {
    }
    return PodMetric;
}());
exports.PodMetric = PodMetric;
var PodMetricUsage = /** @class */ (function () {
    function PodMetricUsage() {
    }
    return PodMetricUsage;
}());
exports.PodMetricUsage = PodMetricUsage;
var PodMetricsListReference = /** @class */ (function () {
    function PodMetricsListReference() {
    }
    PodMetricsListReference.getAttributeTypeMap = function () {
        return PodMetricsListReference.attributeTypeMap;
    };
    PodMetricsListReference.discriminator = undefined;
    PodMetricsListReference.attributeTypeMap = [
        {
            "name": "apiVersion",
            "baseName": "apiVersion",
            "type": "string"
        },
        {
            "name": "items",
            "baseName": "items",
            "type": "Array<PodMetricReference>"
        },
        {
            "name": "kind",
            "baseName": "kind",
            "type": "string"
        },
        {
            "name": "metadata",
            "baseName": "metadata",
            "type": "V1ListMeta"
        }
    ];
    return PodMetricsListReference;
}());
exports.PodMetricsListReference = PodMetricsListReference;
var PodMetricReference = /** @class */ (function () {
    function PodMetricReference() {
    }
    PodMetricReference.getAttributeTypeMap = function () {
        return PodMetricReference.attributeTypeMap;
    };
    PodMetricReference.discriminator = undefined;
    PodMetricReference.attributeTypeMap = [
        {
            "name": "containers",
            "baseName": "containers",
            "type": "Array<PodMetricContainerReference>"
        },
        {
            "name": "timestamp",
            "baseName": "timestamp",
            "type": "Date"
        },
        {
            "name": "window",
            "baseName": "window",
            "type": "string"
        },
        {
            "name": "metadata",
            "baseName": "metadata",
            "type": "V1ListMeta"
        }
    ];
    return PodMetricReference;
}());
exports.PodMetricReference = PodMetricReference;
var PodMetricContainerReference = /** @class */ (function () {
    function PodMetricContainerReference() {
    }
    PodMetricContainerReference.getAttributeTypeMap = function () {
        return PodMetricContainerReference.attributeTypeMap;
    };
    PodMetricContainerReference.discriminator = undefined;
    PodMetricContainerReference.attributeTypeMap = [
        {
            "name": "name",
            "baseName": "name",
            "type": "string"
        },
        {
            "name": "usage",
            "baseName": "usage",
            "type": "PodMetricContainerUsageReference"
        }
    ];
    return PodMetricContainerReference;
}());
exports.PodMetricContainerReference = PodMetricContainerReference;
var PodMetricContainerUsageReference = /** @class */ (function () {
    function PodMetricContainerUsageReference() {
    }
    PodMetricContainerUsageReference.getAttributeTypeMap = function () {
        return PodMetricContainerUsageReference.attributeTypeMap;
    };
    PodMetricContainerUsageReference.discriminator = undefined;
    PodMetricContainerUsageReference.attributeTypeMap = [
        {
            "name": "cpu",
            "baseName": "cpu",
            "type": "string"
        },
        {
            "name": "memory",
            "baseName": "memory",
            "type": "string"
        }
    ];
    return PodMetricContainerUsageReference;
}());
exports.PodMetricContainerUsageReference = PodMetricContainerUsageReference;
var enumsMap = {};
var typeMap = {
    "PodMetricsList": PodMetricsListReference,
    "PodMetricReference": PodMetricReference,
    "PodMetricContainerReference": PodMetricContainerReference,
    "PodMetricContainerUsageReference": PodMetricContainerUsageReference
};
//# sourceMappingURL=KubeUtil.js.map