import "antd/es/card/style";
import _Card from "antd/es/card";
import "antd/es/switch/style";
import _Switch from "antd/es/switch";
import "antd/es/notification/style";
import _notification from "antd/es/notification";
import "antd/es/tooltip/style";
import _Tooltip from "antd/es/tooltip";
import "antd/es/button/style";
import _Button from "antd/es/button";
import "antd/es/avatar/style";
import _Avatar from "antd/es/avatar";
import "antd/es/anchor/style";
import _Anchor from "antd/es/anchor";
import "antd/es/layout/style";
import _Layout from "antd/es/layout";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import React, { useState, useEffect } from 'react';
import { EyeFilled, SettingFilled } from '@ant-design/icons';
import { omit } from 'lodash';
import Ajv from 'ajv'; // @ts-ignore

import { PanelSection } from '@api7-dashboard/ui';
import PluginDrawer from './PluginDrawer';
import { getList, fetchPluginSchema } from './service';
import { transformPlugin } from './transformer';
import { PLUGIN_MAPPER_SOURCE } from './data';
import CodeMirrorDrawer from './CodeMirrorDrawer';
var PanelSectionStyle = {
  display: 'grid',
  gridTemplateColumns: 'repeat(3, 33.333333%)',
  gridRowGap: 15,
  gridColumnGap: 10,
  width: 'calc(100% - 20px)'
};
var Sider = _Layout.Sider,
    Content = _Layout.Content;

var PluginPageApp = function PluginPageApp(_ref) {
  var _ref$initialData = _ref.initialData,
      initialData = _ref$initialData === void 0 ? {} : _ref$initialData,
      readonly = _ref.readonly,
      _ref$onChange = _ref.onChange,
      _onChange = _ref$onChange === void 0 ? function () {} : _ref$onChange;

  var _useState = useState(),
      _useState2 = _slicedToArray(_useState, 2),
      pluginName = _useState2[0],
      setPluginName = _useState2[1];

  var _useState3 = useState(),
      _useState4 = _slicedToArray(_useState3, 2),
      schema = _useState4[0],
      setSchema = _useState4[1];

  var _useState5 = useState([]),
      _useState6 = _slicedToArray(_useState5, 2),
      allPlugins = _useState6[0],
      setAllPlugins = _useState6[1];

  var _useState7 = useState(),
      _useState8 = _slicedToArray(_useState7, 2),
      codeMirrorCodes = _useState8[0],
      setCodeMirrorCodes = _useState8[1];

  useEffect(function () {
    getList(initialData).then(setAllPlugins);
  }, [initialData]);
  var ajv = new Ajv();
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("style", null, "\n        .ant-avatar > img {\n          object-fit: contain;\n        }\n        .ant-avatar {\n          background-color: transparent;\n        }\n        .ant-avatar.ant-avatar-icon {\n          font-size: 32px;\n        }\n      "), /*#__PURE__*/React.createElement(_Layout, null, /*#__PURE__*/React.createElement(Sider, {
    theme: "light"
  }, /*#__PURE__*/React.createElement(_Anchor, {
    offsetTop: 150
  }, allPlugins.map(function (plugins) {
    var category = plugins[0].category;
    return /*#__PURE__*/React.createElement(_Anchor.Link, {
      href: "#plugin-category-".concat(category),
      title: category,
      key: category
    });
  }))), /*#__PURE__*/React.createElement(Content, {
    style: {
      padding: '0 10px',
      backgroundColor: '#fff',
      minHeight: 1400
    }
  }, allPlugins.map(function (plugins) {
    var category = plugins[0].category;
    return /*#__PURE__*/React.createElement(PanelSection, {
      title: category,
      key: category,
      style: PanelSectionStyle,
      id: "plugin-category-".concat(category)
    }, plugins.map(function (_ref2) {
      var _PLUGIN_MAPPER_SOURCE;

      var name = _ref2.name,
          enabled = _ref2.enabled,
          avatar = _ref2.avatar;
      return /*#__PURE__*/React.createElement(_Card, {
        key: name,
        title: [avatar && /*#__PURE__*/React.createElement(_Avatar, {
          icon: avatar,
          className: "plugin-avatar",
          style: {
            marginRight: 5
          }
        }), /*#__PURE__*/React.createElement("a", {
          href: "https://github.com/apache/incubator-apisix/blob/master/doc/plugins/".concat(name, ".md"),
          style: {
            color: 'inherit'
          },
          target: "_blank"
        }, name)],
        style: {
          height: 66
        },
        extra: [/*#__PURE__*/React.createElement(_Tooltip, {
          title: "View Raw",
          key: "plugin-card-".concat(name, "-extra-tooltip")
        }, /*#__PURE__*/React.createElement(_Button, {
          shape: "circle",
          icon: /*#__PURE__*/React.createElement(EyeFilled, null),
          size: "middle",
          onClick: function onClick() {
            setCodeMirrorCodes(initialData[name]);
          }
        })), /*#__PURE__*/React.createElement(_Tooltip, {
          title: "Setting",
          key: "plugin-card-".concat(name, "-extra-tooltip-2")
        }, /*#__PURE__*/React.createElement(_Button, {
          disabled: (_PLUGIN_MAPPER_SOURCE = PLUGIN_MAPPER_SOURCE[name]) === null || _PLUGIN_MAPPER_SOURCE === void 0 ? void 0 : _PLUGIN_MAPPER_SOURCE.noConfiguration,
          shape: "circle",
          icon: /*#__PURE__*/React.createElement(SettingFilled, null),
          style: {
            marginRight: 10,
            marginLeft: 10
          },
          size: "middle",
          onClick: function onClick() {
            fetchPluginSchema(name).then(function (schemaData) {
              setSchema(schemaData);
              setTimeout(function () {
                setPluginName(name);
              }, 300);
            });
          }
        })), /*#__PURE__*/React.createElement(_Switch, {
          defaultChecked: enabled,
          disabled: readonly,
          onChange: function onChange(isChecked) {
            // NOTE: 当前生命周期为：若关闭插件，则移除数据状态；再启用时，该插件一定是没有状态的。
            if (isChecked) {
              var data = initialData[name] || {};
              fetchPluginSchema(name).then(function (schemaData) {
                var validate = ajv.validate(schemaData, data);

                if (validate) {
                  _onChange(_objectSpread(_objectSpread({}, initialData), {}, _defineProperty({}, name, data)));
                } else {
                  _notification.warning({
                    message: "\u8BF7\u914D\u7F6E\u63D2\u4EF6 ".concat(name)
                  });

                  setSchema(schemaData);
                  setTimeout(function () {
                    setPluginName(name);
                  }, 300);
                }
              });
            } else {
              _onChange(omit(_objectSpread({}, initialData), [name]));
            }
          },
          key: Math.random().toString(36).substring(7)
        })]
      });
    }));
  }))), /*#__PURE__*/React.createElement(PluginDrawer, {
    name: pluginName,
    initialData: pluginName ? transformPlugin(pluginName, initialData[pluginName], 'response') : {},
    readonly: readonly,
    schema: schema,
    onClose: function onClose() {
      setPluginName(undefined);
    },
    onFinish: function onFinish(value) {
      if (!pluginName) {
        return;
      }

      _onChange(_objectSpread(_objectSpread({}, initialData), {}, _defineProperty({}, pluginName, transformPlugin(pluginName, value, 'request'))));

      setPluginName(undefined);
    }
  }), /*#__PURE__*/React.createElement(CodeMirrorDrawer, {
    visiable: Boolean(codeMirrorCodes),
    data: codeMirrorCodes || {},
    onClose: function onClose() {
      return setCodeMirrorCodes(undefined);
    }
  }));
};

export default PluginPageApp;