import * as _ from 'lodash';
import * as k8sActions from '../../../app/k8s/actions/k8s';
import { CustomError } from '../../error/custom-error';
import { getReferenceForModel } from '../k8s-ref';
export class NoModelError extends CustomError {
    constructor() {
        super('Model does not exist');
    }
}
export const makeReduxID = (k8sKind, query) => {
    let qs = '';
    if (!_.isEmpty(query)) {
        qs = `---${JSON.stringify(query)}`;
    }
    return `${getReferenceForModel(k8sKind || {})}${qs}`;
};
export const makeQuery = (namespace, labelSelector, fieldSelector, name, limit) => {
    const query = {};
    if (!_.isEmpty(labelSelector)) {
        query.labelSelector = labelSelector;
    }
    if (!_.isEmpty(namespace)) {
        query.ns = namespace;
    }
    if (!_.isEmpty(name)) {
        query.name = name;
    }
    if (fieldSelector) {
        query.fieldSelector = fieldSelector;
    }
    if (limit) {
        query.limit = limit;
    }
    return query;
};
export const INTERNAL_REDUX_IMMUTABLE_TOARRAY_CACHE_SYMBOL = Symbol('_cachedToArrayResult');
export const INTERNAL_REDUX_IMMUTABLE_TOJSON_CACHE_SYMBOL = Symbol('_cachedToJSONResult');
export const getReduxData = (immutableData, resource) => {
    if (!immutableData) {
        return null;
    }
    if (resource.isList && immutableData.toArray) {
        if (!immutableData[INTERNAL_REDUX_IMMUTABLE_TOARRAY_CACHE_SYMBOL]) {
            immutableData[INTERNAL_REDUX_IMMUTABLE_TOARRAY_CACHE_SYMBOL] = immutableData
                .toArray()
                .map((a) => {
                if (a.toJSON) {
                    if (!a[INTERNAL_REDUX_IMMUTABLE_TOJSON_CACHE_SYMBOL]) {
                        a[INTERNAL_REDUX_IMMUTABLE_TOJSON_CACHE_SYMBOL] = a.toJSON();
                    }
                    return a[INTERNAL_REDUX_IMMUTABLE_TOJSON_CACHE_SYMBOL];
                }
                return a;
            });
        }
        return immutableData[INTERNAL_REDUX_IMMUTABLE_TOARRAY_CACHE_SYMBOL];
    }
    if (immutableData.toJSON) {
        if (!immutableData[INTERNAL_REDUX_IMMUTABLE_TOJSON_CACHE_SYMBOL]) {
            immutableData[INTERNAL_REDUX_IMMUTABLE_TOJSON_CACHE_SYMBOL] = immutableData.toJSON();
        }
        return immutableData[INTERNAL_REDUX_IMMUTABLE_TOJSON_CACHE_SYMBOL];
    }
    return null;
};
export const getIDAndDispatch = (resource, k8sModel) => {
    if (!k8sModel || !resource) {
        return null;
    }
    const query = makeQuery(resource.namespace, resource.selector, resource.fieldSelector, resource.name, resource.limit);
    const id = makeReduxID(k8sModel, query);
    const dispatch = resource.isList
        ? k8sActions.watchK8sList(id, query, k8sModel, null, resource.partialMetadata)
        : k8sActions.watchK8sObject(id, resource.name, resource.namespace, query, k8sModel, resource.partialMetadata);
    return { id, dispatch };
};
//# sourceMappingURL=k8s-watcher.js.map