"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const services_1 = require("../services");
const apis_1 = require("../services/apis");
const useUISettings = (clusterId) => {
    const [uiSettings, setUISettings] = react_1.default.useState();
    const [loading, setLoading] = react_1.default.useState(true);
    const [error, setError] = react_1.default.useState('');
    const updateUISettings = react_1.default.useCallback((newSettings) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        if (clusterId) {
            const updatedSettings = Object.assign(Object.assign({}, uiSettings), newSettings);
            try {
                yield services_1.UISettingService.update(clusterId, updatedSettings);
                setUISettings(updatedSettings);
            }
            catch (e) {
                throw new Error();
            }
        }
    }), [clusterId, uiSettings]);
    react_1.default.useEffect(() => {
        const handleUISettingsError = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
            if (clusterId) {
                try {
                    const { data: customManifests } = yield apis_1.ClustersAPI.getManifests(clusterId);
                    const mockUISettings = {
                        customManifestsAdded: customManifests.some((manifest) => manifest.manifestSource === 'user'),
                    };
                    setUISettings(mockUISettings);
                }
                catch (error) {
                    setError('Failed to retrieve cluster custom manifests information');
                }
            }
        });
        const fetchUISettings = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
            if (clusterId) {
                try {
                    const settings = yield services_1.UISettingService.fetch(clusterId);
                    setUISettings(settings);
                }
                catch (e) {
                    yield handleUISettingsError();
                }
            }
            else {
                setUISettings({});
            }
            setLoading(false);
        });
        if (!uiSettings) {
            void fetchUISettings();
        }
    }, [clusterId, setUISettings, uiSettings]);
    const returnValue = react_1.default.useMemo(() => ({ uiSettings, loading, error, updateUISettings }), [uiSettings, loading, error, updateUISettings]);
    return returnValue;
};
exports.default = useUISettings;
//# sourceMappingURL=useUISettings.js.map