"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useDowloadSourceFlyoutForm = useDowloadSourceFlyoutForm;
exports.validateHost = validateHost;
var _react = require("react");
var _i18n = require("@kbn/i18n");
var _hooks = require("../../../../hooks");
var _use_confirm_modal = require("../../hooks/use_confirm_modal");
var _confirm_update = require("./confirm_update");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

function useDowloadSourceFlyoutForm(onSuccess, downloadSource) {
  var _downloadSource$name, _downloadSource$is_de, _downloadSource$host, _downloadSource$proxy;
  const [isLoading, setIsloading] = (0, _react.useState)(false);
  const {
    notifications
  } = (0, _hooks.useStartServices)();
  const {
    confirm
  } = (0, _use_confirm_modal.useConfirmModal)();
  const nameInput = (0, _hooks.useInput)((_downloadSource$name = downloadSource === null || downloadSource === void 0 ? void 0 : downloadSource.name) !== null && _downloadSource$name !== void 0 ? _downloadSource$name : '', validateName);
  const defaultDownloadSourceInput = (0, _hooks.useSwitchInput)((_downloadSource$is_de = downloadSource === null || downloadSource === void 0 ? void 0 : downloadSource.is_default) !== null && _downloadSource$is_de !== void 0 ? _downloadSource$is_de : false, downloadSource === null || downloadSource === void 0 ? void 0 : downloadSource.is_default);
  const hostInput = (0, _hooks.useInput)((_downloadSource$host = downloadSource === null || downloadSource === void 0 ? void 0 : downloadSource.host) !== null && _downloadSource$host !== void 0 ? _downloadSource$host : '', validateHost);
  const proxyIdInput = (0, _hooks.useInput)((_downloadSource$proxy = downloadSource === null || downloadSource === void 0 ? void 0 : downloadSource.proxy_id) !== null && _downloadSource$proxy !== void 0 ? _downloadSource$proxy : '', () => undefined);
  const inputs = {
    nameInput,
    hostInput,
    defaultDownloadSourceInput,
    proxyIdInput
  };
  const hasChanged = Object.values(inputs).some(input => input.hasChanged);
  const validate = (0, _react.useCallback)(() => {
    const nameInputValid = nameInput.validate();
    const hostValid = hostInput.validate();
    return nameInputValid && hostValid;
  }, [nameInput, hostInput]);
  const submit = (0, _react.useCallback)(async () => {
    try {
      if (!validate()) {
        return;
      }
      setIsloading(true);
      const data = {
        name: nameInput.value.trim(),
        host: hostInput.value.trim(),
        is_default: defaultDownloadSourceInput.value,
        proxy_id: proxyIdInput.value || null
      };
      if (downloadSource) {
        // Update
        if (!(await (0, _confirm_update.confirmUpdate)(downloadSource, confirm))) {
          setIsloading(false);
          return;
        }
        const res = await (0, _hooks.sendPutDownloadSource)(downloadSource.id, data);
        if (res.error) {
          throw res.error;
        }
      } else {
        // Create
        const res = await (0, _hooks.sendPostDownloadSource)(data);
        if (res.error) {
          throw res.error;
        }
      }
      onSuccess();
      setIsloading(false);
    } catch (err) {
      setIsloading(false);
      notifications.toasts.addError(err, {
        title: _i18n.i18n.translate('xpack.fleet.settings.dowloadSourceFlyoutForm.errorToastTitle', {
          defaultMessage: 'Error while saving binary source'
        })
      });
    }
  }, [confirm, defaultDownloadSourceInput.value, downloadSource, hostInput.value, nameInput.value, notifications.toasts, onSuccess, proxyIdInput.value, validate]);
  return {
    inputs,
    submit,
    isLoading,
    isDisabled: isLoading || downloadSource && !hasChanged
  };
}
function validateName(value) {
  if (!value || value === '') {
    return [_i18n.i18n.translate('xpack.fleet.settings.dowloadSourceFlyoutForm.nameIsRequiredErrorMessage', {
      defaultMessage: 'Name is required'
    })];
  }
}
function validateHost(value) {
  try {
    if (!value) {
      return [_i18n.i18n.translate('xpack.fleet.settings.dowloadSourceFlyoutForm.HostIsRequiredErrorMessage', {
        defaultMessage: 'Host is required'
      })];
    }
    const urlParsed = new URL(value);
    if (!['http:', 'https:'].includes(urlParsed.protocol)) {
      throw new Error('Invalid protocol');
    }
  } catch (error) {
    return [_i18n.i18n.translate('xpack.fleet.settings.dowloadSourceFlyoutForm.hostError', {
      defaultMessage: 'Invalid URL'
    })];
  }
}