define(['exports', './TopicsListComponent-d0f74d18', 'react', 'react-router-dom', 'prop-types', 'react-helmet', 'react-intl', 'react-redux', 'redux', 'reselect', 'react-bootstrap/Form', 'react-bootstrap/Button', './index-ba8ec889', './request-ddfa17c1', './selectors-5abc75bf', 'styled-components', 'immer', 'redux-saga/effects', 'js-cookie', 'sanitize.css/sanitize.css', 'connected-react-router', 'redux-saga', 'history', 'hoist-non-react-statics', 'invariant', 'lodash'], function (exports, TopicsListComponent, React, reactRouterDom, PropTypes, reactHelmet, reactIntl, reactRedux, redux, reselect, Form, Button, index$1, request, selectors, styled, produce, effects, Cookies, sanitize_css, connectedReactRouter, createSagaMiddleware, history, hoistNonReactStatics, invariant, lodash) { 'use strict';

  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

  var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
  var PropTypes__default = /*#__PURE__*/_interopDefaultLegacy(PropTypes);
  var Form__default = /*#__PURE__*/_interopDefaultLegacy(Form);
  var Button__default = /*#__PURE__*/_interopDefaultLegacy(Button);
  var styled__default = /*#__PURE__*/_interopDefaultLegacy(styled);
  var produce__default = /*#__PURE__*/_interopDefaultLegacy(produce);
  var Cookies__default = /*#__PURE__*/_interopDefaultLegacy(Cookies);

  const Section = styled__default['default'].section.withConfig({
    displayName: "Section",
    componentId: "nqaf7u-0"
  })(["margin:3em auto;&:first-child{margin-top:0;}"]);

  const CenteredSection = styled__default['default'](Section).withConfig({
    displayName: "CenteredSection",
    componentId: "sc-13yt1m2-0"
  })(["text-align:center;"]);

  /*
   * HomePage Messages
   *
   * This contains all the text for the HomePage component.
   */
  const scope = 'boilerplate.containers.HomePage';
  var messages = reactIntl.defineMessages({
    newTopicHeader: {
      id: `${scope}.newtopic.header`,
      defaultMessage: 'Create new Topic'
    },
    title: {
      id: `${scope}.title`,
      defaultMessage: 'Title'
    },
    description: {
      id: `${scope}.description`,
      defaultMessage: 'Description'
    },
    submitButton: {
      id: `${scope}.submitButton`,
      defaultMessage: 'Submit'
    }
  });

  /*
   * HomeConstants
   * Each action has a corresponding type, which the reducer knows and picks up on.
   * To avoid weird typos between the reducer and the actions, we save them as
   * constants here. We prefix them with 'yourproject/YourComponent' so we avoid
   * reducers accidentally picking up actions they shouldn't.
   *
   * Follow this format:
   * export const YOUR_ACTION_CONSTANT = 'yourproject/YourContainer/YOUR_ACTION_CONSTANT';
   */
  const NEW_TOPIC = 'reactCommentsDjango/NewTopicPage/NEW_TOPIC';
  const NEW_TOPIC_SUCCESS = 'reactCommentsDjango/NewTopicPage/NEW_TOPIC_SUCCESS';

  /*
   * Home Actions
   *
   * Actions change things in your application
   * Since this boilerplate uses a uni-directional data flow, specifically redux,
   * we have these actions which are the only way your application interacts with
   * your application state. This guarantees that your state is up to date and nobody
   * messes it up weirdly somewhere.
   *
   * To add a new Action:
   * 1) Import your constant
   * 2) Add a function like this:
   *    export function yourAction(var) {
   *        return { type: YOUR_ACTION_CONSTANT, var: var }
   *    }
   */
  /**
   * newTopic, this action starts the request saga
   *
   * @return {object} An action object with a type of LOAD_REPOS
   */

  function newTopic$1(formData) {
    return {
      type: NEW_TOPIC,
      formData
    };
  }
  /**
   * Dispatched when the repositories are loaded by the request saga
   *
   * @param  {array} repos The repository data
   * @param  {string} username The current username
   *
   * @return {object}      An action object with a type of LOAD_REPOS_SUCCESS passing the repos
   */

  function newTopicSuccess(user) {
    return {
      type: NEW_TOPIC_SUCCESS,
      user
    };
  }

  var newtopicCreators = /*#__PURE__*/Object.freeze({
    __proto__: null,
    newTopic: newTopic$1,
    newTopicSuccess: newTopicSuccess
  });

  /*
   * HomeReducer
   *
   * The reducer takes care of our data. Using actions, we can
   * update our application state. To add a new action,
   * add it to the switch statement in the reducer function
   *
   */

  const initialState = {
    user: {}
  };
  /* eslint-disable default-case, no-param-reassign */

  const newTopicReducer = (state = initialState, action) => produce__default['default'](state, draft => {
    switch (action.type) {
      case NEW_TOPIC:
        draft.loading = true;
        break;

      case NEW_TOPIC_SUCCESS:
        draft.loading = false;
        draft.user = action.user;
        break;
    }
  });

  function newTopicCall(data) {
    const csrftoken = Cookies__default['default'].get('csrftoken'); // const formData = new FormData()
    // Object.keys(data).forEach(key => formData.append(key, data[key]))
    // const searchParams = Object.keys(data)
    //   .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
    //   .join('&')

    return request.request(`${index$1.API_PREFIX}topics/`, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-CSRFToken': csrftoken,
        'X-Requested-With': 'XMLHttpRequest'
      },
      body: JSON.stringify(data) // body: JSON.stringify(
      //   Object.assign({}, formData, { csrfmiddlewaretoken: csrftoken }),
      // ),

    });
  }

  const Api = {
    newTopicCall
  };

  /**
   * Gets the repositories of the user from Github
   */
  function* newTopic(action) {
    // Select username from store
    // const formData = yield select(makeSelectFormData())
    // const requestURL = `https://api.github.com/users/${username}/repos?type=all&sort=updated`
    try {
      // const success = yield Api.newTopicCall(action.formData)
      yield effects.call(Api.newTopicCall, action.formData);
      yield effects.call(() => {
        // move to topics list
        // window.location.href = '/topics'
        TopicsListComponent.history.push('/topics');
      }); // yield put(newTopicSuccess(userData))
    } catch (err) {
      // yield put(repoLoadingError(err))
      yield effects.call(() => {
        console.log(err);
      });
    }
  }
  /**
   * Root saga manages watcher lifecycle
   */

  function* newTopicData() {
    // Watches for NEW_TOPIC actions and calls getRepos when one comes in.
    // By using `takeLatest` only the result of the latest API call is applied.
    // It returns task descriptor (just like fork) so we can continue execution
    // It will be cancelled automatically on component unmount
    yield effects.takeLatest(NEW_TOPIC, newTopic);
  }

  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) { TopicsListComponent._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; }
  const key = 'newtopic';
  function NewTopicPage({
    // username,
    // loading,
    // error,
    signedInUser,
    // onSubmitForm,
    newTopicActions,
    intl // onChangeUsername,

  }) {
    index$1.useInjectReducer({
      key,
      reducer: newTopicReducer
    });
    request.useInjectSaga({
      key,
      saga: newTopicData
    });
    const formList = ['title', 'description']; // const formList = ['title']

    const formDict = formList.reduce((_obj, x) => {
      const obj = Object.assign({}, _obj);
      obj[x] = '';
      return obj;
    }, {});
    const [formData, setFormData] = React.useState(formDict);
    const [errors, setErrors] = React.useState({});
    const [submitDisabled, setSubmitDisabled] = React.useState(true);

    const validateForm = () => {
      const errors = {};
      formList.forEach(function (formKey) {
        if (formKey != 'description' && !formData[formKey]) {
          errors[formKey] = `${formKey} is required`;
        }
      });
      return errors;
    }; // const handleChange = (event, { name, value }) => {
    //   setFormData(prevState => ({ ...prevState, [name]: value }))
    // }


    const handleChange = event => {
      const {
        name
      } = event.target;
      const {
        value
      } = event.target;
      setFormData(prevState => _objectSpread(_objectSpread({}, prevState), {}, {
        [name]: value
      }));
    };

    React.useEffect(() => {
      const validationErrors = validateForm();

      if (Object.keys(validationErrors).length === 0 && validationErrors.constructor === Object) {
        setSubmitDisabled(false);
      } else {
        setSubmitDisabled(true);
      }

      setErrors(validationErrors);
    }, [formData]);

    const handleSubmit = event => {
      event.preventDefault();
      event.stopPropagation();
      newTopicActions.newTopic(formData);
    };

    if (signedInUser === undefined) {
      // user loading false / todo it is better to use signedInUserError value
      return /*#__PURE__*/React__default['default'].createElement(reactRouterDom.Redirect, {
        to: {
          pathname: '/signin'
        }
      });
    }
    /* TODO create this form based on OPTION API call */

    /* TODO add validation errors info */


    return /*#__PURE__*/React__default['default'].createElement("article", null, /*#__PURE__*/React__default['default'].createElement(reactHelmet.Helmet, null, /*#__PURE__*/React__default['default'].createElement("title", null, "New topic"), /*#__PURE__*/React__default['default'].createElement("meta", {
      name: "description",
      content: "React comments django new topic page"
    })), /*#__PURE__*/React__default['default'].createElement("div", null, /*#__PURE__*/React__default['default'].createElement(CenteredSection, null, /*#__PURE__*/React__default['default'].createElement(index$1.H2, null, /*#__PURE__*/React__default['default'].createElement(reactIntl.FormattedMessage, messages.newTopicHeader))), /*#__PURE__*/React__default['default'].createElement(Section, null, /*#__PURE__*/React__default['default'].createElement(Form__default['default'], {
      onSubmit: handleSubmit
    }, /*#__PURE__*/React__default['default'].createElement(Form__default['default'].Group, null, /*#__PURE__*/React__default['default'].createElement("label", null, /*#__PURE__*/React__default['default'].createElement(reactIntl.FormattedHTMLMessage, messages.title)), /*#__PURE__*/React__default['default'].createElement(Form__default['default'].Control, {
      required: true,
      type: "text" // label={intl.formatMessage(messages.title)}
      ,
      value: formData.title,
      onChange: handleChange,
      name: "title"
    })), /*#__PURE__*/React__default['default'].createElement(Form__default['default'].Group, null, /*#__PURE__*/React__default['default'].createElement("label", null, /*#__PURE__*/React__default['default'].createElement(reactIntl.FormattedHTMLMessage, messages.description)), /*#__PURE__*/React__default['default'].createElement(Form__default['default'].Control, {
      // label={intl.formatMessage(messages.description)}
      value: formData.description,
      type: "textarea",
      name: "description",
      onChange: handleChange
    })), /*#__PURE__*/React__default['default'].createElement(Button__default['default'], {
      type: "submit",
      disabled: submitDisabled
    }, /*#__PURE__*/React__default['default'].createElement(reactIntl.FormattedMessage, messages.submitButton))))));
  }
  NewTopicPage.propTypes = {
    newTopicActions: PropTypes__default['default'].shape({
      newTopic: PropTypes__default['default'].func.isRequired
    }).isRequired,
    signedInUser: PropTypes__default['default'].oneOfType([PropTypes__default['default'].object, PropTypes__default['default'].bool]) // loading: PropTypes.bool,
    // error: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
    // repos: PropTypes.oneOfType([PropTypes.array, PropTypes.bool]),
    // onSubmitForm: PropTypes.func,
    // username: PropTypes.string,
    // onChangeUsername: PropTypes.func,

  };
  const mapStateToProps = reselect.createStructuredSelector({
    // repos: makeSelectRepos(),
    signedInUser: selectors.makeSelectSignedInUser() // user: makeSelectUser(),
    // formData: makeSelectFormData(),
    // loading: makeSelectLoading(),
    // error: makeSelectError(),

  });
  function mapDispatchToProps(dispatch) {
    return {
      // onChangeUsername: evt => dispatch(changeUsername(evt.target.value)),
      newTopicActions: redux.bindActionCreators(newtopicCreators, dispatch) // onSubmitForm: evt => {
      //   if (evt !== undefined && evt.preventDefault) evt.preventDefault()
      //   // dispatch(loadRepos())
      //   dispatch(newTopic())
      // },

    };
  }
  const withConnect = reactRedux.connect(mapStateToProps, mapDispatchToProps);
  var index = redux.compose(withConnect, React.memo)(reactIntl.injectIntl(NewTopicPage));

  exports.NewTopicPage = NewTopicPage;
  exports.default = index;
  exports.mapDispatchToProps = mapDispatchToProps;

});
//# sourceMappingURL=index-9c7e90c1.js.map
