import _regeneratorRuntime from "@babel/runtime/regenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _createForOfIteratorHelper from "@babel/runtime/helpers/esm/createForOfIteratorHelper";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useState } from "react";
import Button from "@material-ui/core/Button";
import { makeStyles } from "@material-ui/core/styles";
import authTemplates from "./authTemplates";
import SimpleDialog from "../SimpleDialog";
import isEmpty from "lodash/isEmpty";
import Survey from "material-survey/components/Survey";
import ErrorToasts from "../ErrorToasts";
import useErrors from "../../hooks/use-errors.js";
import Amplify from "aws-amplify";
import { useAppConfig } from "../AppConfig";
import * as colors from "@material-ui/core/colors";
import { useTranslation } from "react-i18next";
var useStyles = makeStyles({
  bigButton: {
    padding: 10,
    width: 150,
    height: 120,
    border: "1px solid #ccc",
    margin: 10
  },
  bigIcon: {
    width: 48,
    height: 48
  },
  cognitoIcon: {
    width: 48,
    height: 48
  },
  howToSetupText: {
    padding: 16,
    color: colors.grey[600],
    "& a": {
      color: colors.blue[500],
      textDecoration: "none"
    }
  }
});
var forms = {
  cognito: {
    questions: [{
      name: "auth.cognito.identityPoolId",
      title: "Amazon Cognito Identity Pool ID",
      placeholder: "XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab",
      type: "text",
      isRequired: true
    }, {
      name: "auth.cognito.region",
      title: "AWS Region",
      placeholder: "XX-XXXX-X",
      type: "text",
      isRequired: true
    }, {
      name: "auth.cognito.userPoolId",
      title: "Amazon Cognito User Pool ID",
      placeholder: "XX-XXXX-X_12ab34cd9",
      type: "text",
      isRequired: true
    }, {
      name: "auth.cognito.userPoolWebClientId",
      title: "Amazon Cognito Web Client ID",
      placeholder: "26-char alphanumeric string",
      type: "text",
      isRequired: true
    }, {
      name: "auth.cognito.storage.awsS3.bucket",
      title: "Bucket AWS",
      placeholder: "Name of the bucket",
      type: "text",
      isRequired: true
    }, {
      name: "auth.cognito.storage.awsS3.region",
      title: "Region of the bucket",
      placeholder: "XX-XXXX-X",
      type: "text",
      isRequired: true
    }, {
      name: "auth.cognito.password.minimumLength",
      title: "Minimum lenght of password",
      type: "text",
      isRequired: true,
      validators: [{
        maxValue: 99,
        minValue: 6,
        text: "Cognito allows password length to be between 6 and 99",
        type: "numeric"
      }]
    }, {
      name: "auth.cognito.password.requireLowercase",
      title: "Require a lowercase letter in password",
      type: "boolean",
      isRequired: true
    }, {
      name: "auth.cognito.password.requireUppercase",
      title: "Require a uppercase letter in password",
      type: "boolean",
      isRequired: true
    }, {
      name: "auth.cognito.password.requireNumbers",
      title: "Require a number in password",
      type: "boolean",
      isRequired: true
    }, {
      name: "auth.cognito.password.requireSymbols",
      title: "Require a symbol in password",
      type: "boolean",
      isRequired: true
    }]
  },
  s3iam: {
    questions: [{
      name: "auth.s3iam.accessKeyId",
      title: "Access Key ID",
      placeholder: "",
      type: "text",
      isRequired: true
    }, {
      name: "auth.s3iam.secretAccessKey",
      title: "Secret Access Key",
      placeholder: "",
      type: "text",
      isRequired: true
    }, {
      name: "auth.s3iam.region",
      title: "Region",
      placeholder: "us-east-1",
      type: "text",
      isRequired: true
    }]
  },
  proxy: {
    questions: [{
      name: "auth.proxy.corsproxy",
      type: "text",
      title: "CORS Proxy",
      description: "Some requests for images or APIs (like AWS S3) are blocked by browsers for security reasons, this CORs proxy will be used to enable blocked functionality when not using the desktop application."
    }]
  }
};
export default (function (_ref) {
  var open = _ref.open,
      _onClose = _ref.onClose,
      onSelect = _ref.onSelect,
      onFinish = _ref.onFinish,
      onAuthConfigured = _ref.onAuthConfigured;
  var c = useStyles();

  var _useTranslation = useTranslation(),
      t = _useTranslation.t;

  var _useState = useState(null),
      _useState2 = _slicedToArray(_useState, 2),
      authProvider = _useState2[0],
      setAuthProvider = _useState2[1];

  var _useState3 = useState(t("add-authentication")),
      _useState4 = _slicedToArray(_useState3, 2),
      dialogTitle = _useState4[0],
      setDialogTitle = _useState4[1];

  var _useErrors = useErrors(),
      _useErrors2 = _slicedToArray(_useErrors, 2),
      errors = _useErrors2[0],
      addError = _useErrors2[1];

  var _useAppConfig = useAppConfig(),
      appConfig = _useAppConfig.appConfig,
      setAppConfig = _useAppConfig.setAppConfig,
      fromConfig = _useAppConfig.fromConfig,
      setInConfig = _useAppConfig.setInConfig;

  var getDefaultsFromConfig = function getDefaultsFromConfig(form) {
    var questionIds = form.questions.map(function (q) {
      return q.name;
    });
    var defaults = {};

    var _iterator = _createForOfIteratorHelper(questionIds),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var questionId = _step.value;
        var configValue = fromConfig(questionId);

        if (configValue !== undefined) {
          defaults[questionId] = configValue;
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return defaults;
  }; // TODO useAppConfig to load in existing configuration


  var validateAuthProvider = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(answers) {
      var config;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (answers.provider === "cognito") {
                config = {
                  Auth: {
                    identityPoolId: answers["auth.cognito.identityPoolId"],
                    region: answers["auth.cognito.region"],
                    userPoolId: answers["auth.cognito.userPoolId"],
                    userPoolWebClientId: answers["auth.cognito.userPoolWebClientId"],
                    mandatorySignIn: true,
                    authenticationFlowType: "USER_PASSWORD_AUTH",
                    minimumLength: answers["auth.cognito.password.minimumLength"],
                    requireNumbers: answers["auth.cognito.password.requireNumbers"],
                    requireSymbols: answers["auth.cognito.password.requireSymbols"],
                    requireUppercase: answers["auth.cognito.password.requireUppercase"],
                    requireLowercase: answers["auth.cognito.password.requireLowercase"]
                  },
                  Storage: {
                    AWSS3: {
                      bucket: answers["auth.cognito.storage.awsS3.bucket"],
                      region: answers["auth.cognito.storage.awsS3.region"]
                    }
                  }
                };

                try {
                  Amplify.configure(config);
                } catch (err) {
                  addError("Invalid Cognito config: " + err.toString());
                }
              }

              setAppConfig(_objectSpread(_objectSpread(_objectSpread({}, appConfig), answers), {}, {
                "auth.provider": answers.provider
              })); // TODO some kind of success message

              _onClose();

              setAuthProvider(null);

            case 4:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function validateAuthProvider(_x) {
      return _ref2.apply(this, arguments);
    };
  }();

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(SimpleDialog, {
    title: dialogTitle,
    open: open,
    onClose: function onClose() {
      _onClose();
    },
    onFinish: onFinish
  }, isEmpty(authProvider) && authTemplates.map(function (template, i) {
    return /*#__PURE__*/React.createElement(Button, {
      key: template.name,
      onClick: function onClick() {
        setAuthProvider(template.provider);
        setDialogTitle("".concat(t("add-authentication"), " ").concat(template.name));
      },
      className: c.bigButton
    }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", null, template.name), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(template.Icon, {
      className: c.cognitoIcon
    }))));
  }), authProvider === "cognito" && /*#__PURE__*/React.createElement("div", {
    className: c.howToSetupText
  }, t("check-this-wiki"), " ", /*#__PURE__*/React.createElement("a", {
    href: "https://github.com/UniversalDataTool/universal-data-tool/wiki/Cognito---Amplify-Authentication-Setup-Instructions"
  }, t("guide-to-set-up-cognito")), "."), !isEmpty(authProvider) && forms[authProvider] && /*#__PURE__*/React.createElement(Survey, {
    variant: "flat",
    form: forms[authProvider],
    onQuestionChange: function onQuestionChange(questionId, newValue) {
      setInConfig(questionId, newValue);
    },
    completeText: t("complete"),
    onFinish: function onFinish(answers) {
      answers["provider"] = authProvider;
      validateAuthProvider(answers);
    },
    defaultAnswers: _objectSpread(_objectSpread({}, getDefaultsFromConfig(forms[authProvider])), {}, {
      "auth.provider": fromConfig("auth.provider")
    })
  }), /*#__PURE__*/React.createElement(ErrorToasts, {
    errors: errors
  })));
});