"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_core_1 = require("@patternfly/react-core");
const error_circle_o_icon_1 = require("@patternfly/react-icons/dist/js/icons/error-circle-o-icon");
const upload_icon_1 = require("@patternfly/react-icons/dist/js/icons/upload-icon");
const js_yaml_1 = tslib_1.__importDefault(require("js-yaml"));
const file_saver_1 = require("file-saver");
const use_translation_wrapper_1 = require("../../../common/hooks/use-translation-wrapper");
const utils_1 = require("../../../common/utils");
const constants_1 = require("./constants");
require("./AddBmcHostYamlForm.css");
const AddBmcHostYamlForm = ({ onClose, onCreateBmcByYaml }) => {
    const [fileName, setFileName] = React.useState();
    const [fileError, setFileError] = React.useState();
    const [showOpenFileButton, setShowOpenFileButton] = React.useState(true);
    const [showOpeningMessage, setShowOpeningMessage] = React.useState(false);
    const [yamlContent, setYamlContent] = React.useState();
    const [error, setError] = React.useState();
    const { t } = (0, use_translation_wrapper_1.useTranslation)();
    const downloadYaml = () => {
        const yaml = [constants_1.credentials, constants_1.host1, constants_1.host2].map((doc) => js_yaml_1.default.dump(doc)).join('---\n');
        const blob = new Blob([yaml], { type: 'text/plain;charset=utf-8' });
        (0, file_saver_1.saveAs)(blob, 'bmc_hosts_template.yaml');
    };
    const importBMAsYAML = () => {
        const input = document.createElement('input');
        input.setAttribute('id', 'importBMAsYaml');
        input.type = 'file';
        input.accept = '.yaml';
        input.style.visibility = 'hidden';
        const body = document.querySelector('body');
        body === null || body === void 0 ? void 0 : body.appendChild(input);
        input.onchange = (e) => {
            setShowOpeningMessage(true);
            input.remove();
            const target = e.target;
            const file = target.files[0];
            const maxSize = 12582912; //12 MiB
            if (file.size > maxSize) {
                setShowOpenFileButton(false);
                setFileName(file.name);
                setFileError(t('ai:The file is too big. Upload a file up to 12 MiB.'));
                setYamlContent(undefined);
            }
            else {
                const reader = new FileReader();
                reader.readAsText(file, 'UTF-8');
                reader.onload = (readerEvent) => {
                    var _a;
                    const content = (_a = readerEvent.target) === null || _a === void 0 ? void 0 : _a.result;
                    // parse yaml
                    if (content && typeof content === 'string') {
                        try {
                            //await new Promise((r) => setTimeout(r, 100));
                            const yamlContent = js_yaml_1.default.loadAll(content);
                            setFileName(file.name);
                            setFileError(undefined);
                            setYamlContent(yamlContent);
                        }
                        catch (err) {
                            setFileName(file.name);
                            setFileError(t('ai:File is not structured correctly. Use the template to use the right file structure.'));
                            setYamlContent(undefined);
                        }
                    }
                    else {
                        setYamlContent(undefined);
                        setFileName(file.name);
                        setFileError(t('ai:File is not structured correctly. Use the template to use the right file structure.'));
                    }
                    setShowOpenFileButton(false);
                };
            }
        };
        input.click();
    };
    const deleteFileContent = () => {
        setFileError(undefined);
        setError(undefined);
        setFileName(undefined);
        setShowOpenFileButton(true);
        setShowOpeningMessage(false);
    };
    const handleSubmit = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        try {
            setShowOpeningMessage(false);
            setError(undefined);
            if (yamlContent !== undefined) {
                yield onCreateBmcByYaml(yamlContent);
            }
            onClose();
        }
        catch (e) {
            setError((0, utils_1.getErrorMessage)(e));
        }
    });
    return (React.createElement(React.Fragment, null,
        React.createElement(react_core_1.ModalBody, null,
            React.createElement(react_core_1.Stack, { hasGutter: true },
                React.createElement(react_core_1.StackItem, null,
                    React.createElement(react_core_1.EmptyState, { headingLevel: "h4", icon: upload_icon_1.UploadIcon, titleText: React.createElement(React.Fragment, null, t('ai:Upload a YAML file')), variant: react_core_1.EmptyStateVariant.lg },
                        React.createElement(react_core_1.EmptyStateBody, null,
                            React.createElement("p", null, t('ai:Upload a YAML file with BareMetalHost and Secret resource definitions. Use the provided template as a reference.')),
                            React.createElement(react_core_1.Stack, { hasGutter: true },
                                React.createElement(react_core_1.StackItem, null,
                                    React.createElement(react_core_1.Button, { variant: react_core_1.ButtonVariant.link, onClick: downloadYaml }, t('ai:Download template'))),
                                showOpenFileButton && (React.createElement(react_core_1.StackItem, null,
                                    React.createElement(react_core_1.Button, { variant: react_core_1.ButtonVariant.secondary, onClick: () => {
                                            try {
                                                importBMAsYAML();
                                            }
                                            catch (e) {
                                                setError((0, utils_1.getErrorMessage)(e));
                                            }
                                        }, isDisabled: showOpeningMessage }, showOpeningMessage ? (React.createElement(React.Fragment, null,
                                        t('ai:Opening file'),
                                        " ",
                                        React.createElement(react_core_1.Spinner, { size: "sm" }))) : (t('ai:Open file'))))),
                                fileName && (React.createElement(react_core_1.StackItem, null,
                                    fileName,
                                    "\u00A0",
                                    React.createElement(error_circle_o_icon_1.ErrorCircleOIcon, { onClick: deleteFileContent }))))))),
                error && (React.createElement(react_core_1.StackItem, null,
                    React.createElement(react_core_1.Alert, { title: t('ai:Failed to add host by YAML'), variant: react_core_1.AlertVariant.danger, isInline: true, actionClose: React.createElement(react_core_1.AlertActionCloseButton, { onClose: () => setError(undefined) }) },
                        t('ai:The YAML file might not be formatted correctly. Use the template to format and try again.'),
                        React.createElement("br", null),
                        t('ai:Received error:'),
                        "\u00A0",
                        error))),
                fileError && (React.createElement(react_core_1.StackItem, null,
                    React.createElement(react_core_1.Alert, { title: t('ai:The file cannot be uploaded'), variant: react_core_1.AlertVariant.danger, isInline: true, actionClose: React.createElement(react_core_1.AlertActionCloseButton /* onClose={() => setFileError(undefined)}*/, null) }, fileError))))),
        React.createElement(react_core_1.ModalFooter, null,
            React.createElement(react_core_1.Button, { onClick: () => {
                    void handleSubmit();
                }, isDisabled: !fileName || !!fileError }, t('ai:Upload')),
            React.createElement(react_core_1.Button, { onClick: onClose, variant: react_core_1.ButtonVariant.secondary }, t('ai:Cancel')))));
};
exports.default = AddBmcHostYamlForm;
//# sourceMappingURL=AddBmcHostYamlForm.js.map