"use strict";

exports.__esModule = true;
exports.default = Location;

var _react = _interopRequireWildcard(require("react"));

var _reactIntl = require("react-intl");

var _Autocomplete = _interopRequireDefault(require("@mui/material/Autocomplete"));

var _TextField = _interopRequireDefault(require("@mui/material/TextField"));

var _CircularProgress = _interopRequireDefault(require("@mui/material/CircularProgress"));

var _core = require("@selfcommunity/core");

var _styles = require("@mui/material/styles");

var _parse = _interopRequireDefault(require("autosuggest-highlight/parse"));

var _match = _interopRequireDefault(require("autosuggest-highlight/match"));

var _useThemeProps = _interopRequireDefault(require("@mui/material/styles/useThemeProps"));

const _excluded = ["defaultValue", "disabled", "onChange", "TextFieldProps"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

const PREFIX = 'SCComposerLocation';
const classes = {
  root: `${PREFIX}-root`
};
const Root = (0, _styles.styled)(_Autocomplete.default, {
  name: PREFIX,
  slot: 'Root',
  overridesResolver: (props, styles) => styles.root
})(() => ({
  minWidth: 120
}));

function Location(inProps) {
  // Props
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: PREFIX
  });

  const {
    defaultValue = null,
    disabled = false,
    onChange,
    TextFieldProps = {
      variant: 'outlined',
      label: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
        id: "ui.composer.location.label",
        defaultMessage: "ui.composer.locations.label"
      })
    }
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // State


  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [locations, setLocations] = (0, _react.useState)([]);
  const [value, setValue] = (0, _react.useState)(defaultValue);
  const [search, setSearch] = (0, _react.useState)('');

  const load = (offset = 0, limit = 20) => {
    _core.http.request({
      url: _core.Endpoints.ComposerLocalitySearch.url(),
      method: _core.Endpoints.ComposerLocalitySearch.method,
      params: {
        offset,
        limit,
        search: search.trim()
      }
    }).then(res => {
      setLocations(res.data.results);
    }).then(() => setIsLoading(false));
  }; // Component update


  (0, _react.useEffect)(() => {
    if (!isLoading && search.trim().length > 0) {
      load();
    }
  }, [search]);
  (0, _react.useEffect)(() => {
    if (value) {
      onChange && onChange(value);
    }
  }, [value]); // Handlers

  const handleChange = (event, value) => {
    setValue(value);
    onChange && onChange(value);
  };

  const handleSearch = (event, _search) => {
    setSearch(_search);
  }; // Render


  return /*#__PURE__*/_react.default.createElement(Root, _extends({
    className: classes.root,
    options: locations || [],
    getOptionLabel: option => option.full_address || '',
    filterOptions: x => x,
    autoComplete: true,
    includeInputInList: true,
    filterSelectedOptions: true,
    value: value,
    selectOnFocus: true,
    handleHomeEndKeys: true,
    disabled: disabled,
    noOptionsText: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.location.empty",
      defaultMessage: "ui.composer.location.empty"
    }),
    onChange: handleChange,
    onInputChange: handleSearch,
    isOptionEqualToValue: (option, value) => value.lat === option.lat && value.lng === option.lng,
    renderInput: params => {
      return /*#__PURE__*/_react.default.createElement(_TextField.default, _extends({}, params, TextFieldProps, {
        margin: "dense",
        InputProps: Object.assign({}, params.InputProps, {
          autoComplete: 'location',
          // disable autocomplete and autofill
          endAdornment: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, isLoading ? /*#__PURE__*/_react.default.createElement(_CircularProgress.default, {
            color: "inherit",
            size: 20
          }) : null, params.InputProps.endAdornment)
        })
      }));
    },
    renderOption: (props, option, {
      inputValue
    }) => {
      const matches = (0, _match.default)(option.full_address, inputValue);
      const parts = (0, _parse.default)(option.full_address, matches);
      return /*#__PURE__*/_react.default.createElement("li", _extends({
        key: `${option.lat}_${option.lng}`
      }, props, {
        style: {
          whiteSpace: 'break-spaces'
        }
      }), parts.map((part, index) => part.highlight ? /*#__PURE__*/_react.default.createElement("span", {
        key: index,
        style: {
          fontWeight: 700
        }
      }, part.text) : part.text));
    }
  }, rest));
}