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', 'react-mde', 'showdown', 'react-mde/lib/styles/css/react-mde-all.css', './request-ddfa17c1', './selectors-5abc75bf', './saga-5fb20c1e', '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, ReactMde, Showdown, reactMdeAll_css, request, selectors, saga, 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 }; }

  function _interopNamespace(e) {
    if (e && e.__esModule) return e;
    var n = Object.create(null);
    if (e) {
      Object.keys(e).forEach(function (k) {
        if (k !== 'default') {
          var d = Object.getOwnPropertyDescriptor(e, k);
          Object.defineProperty(n, k, d.get ? d : {
            enumerable: true,
            get: function () {
              return e[k];
            }
          });
        }
      });
    }
    n['default'] = e;
    return Object.freeze(n);
  }

  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 ReactMde__default = /*#__PURE__*/_interopDefaultLegacy(ReactMde);
  var Showdown__namespace = /*#__PURE__*/_interopNamespace(Showdown);
  var styled__default = /*#__PURE__*/_interopDefaultLegacy(styled);
  var produce__default = /*#__PURE__*/_interopDefaultLegacy(produce);
  var Cookies__default = /*#__PURE__*/_interopDefaultLegacy(Cookies);

  function ContentEditor(props) {
    const [mdeTab, setMdeTab] = React.useState('write');
    const [content, setContent] = React.useState(props.initialValue || '');

    const handleContentChange = val => {
      // setFormData(prevState => ({ ...prevState, content: val }))
      setContent(val);
      props.onContentChange(val);
    };

    const handleTabChange = tab => {
      setMdeTab(tab);
    };

    const markdownConverter = new Showdown__namespace.Converter({
      tables: true,
      simplifiedAutoLink: true,
      strikethrough: true,
      tasklists: true
    });
    return /*#__PURE__*/React__default['default'].createElement(ReactMde__default['default'], {
      onChange: handleContentChange,
      value: content,
      onTabChange: handleTabChange,
      selectedTab: mdeTab,
      generateMarkdownPreview: markdown => Promise.resolve(markdownConverter.makeHtml(markdown))
    });
  }

  ContentEditor.propTypes = {
    // className: PropTypes.string,
    onContentChange: PropTypes__default['default'].func.isRequired,
    initialValue: PropTypes__default['default'].string
  };

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

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

  /*
   * HomePage Messages
   *
   * This contains all the text for the HomePage component.
   */
  const scope = 'boilerplate.containers.HomePage';
  var messages = reactIntl.defineMessages({
    newThreadHeader: {
      id: `${scope}.newThread.header`,
      defaultMessage: 'Create new thread'
    },
    title: {
      id: `${scope}.title`,
      defaultMessage: 'Title'
    },
    content: {
      id: `${scope}.content`,
      defaultMessage: 'Content'
    },
    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_THREAD = 'reactCommentsDjango/NewThreadPage/NEW_THREAD';
  const NEW_THREAD_SUCCESS = 'reactCommentsDjango/NewThreadPage/NEW_THREAD_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 }
   *    }
   */
  /**
   * newThread, this action starts the request saga
   *
   * @return {object} An action object with a type of LOAD_REPOS
   */

  function newThread$1(formData) {
    return {
      type: NEW_THREAD,
      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 newThreadSuccess(user) {
    return {
      type: NEW_THREAD_SUCCESS,
      user
    };
  }

  var newThreadCreators = /*#__PURE__*/Object.freeze({
    __proto__: null,
    newThread: newThread$1,
    newThreadSuccess: newThreadSuccess
  });

  /*
   * 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 newThreadReducer = (state = initialState, action) => produce__default['default'](state, draft => {
    switch (action.type) {
      case NEW_THREAD:
        draft.loading = true;
        break;

      case NEW_THREAD_SUCCESS:
        draft.loading = false;
        draft.thread = action.thread;
        break;
    }
  });

  function newThreadCall(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}threads/`, {
      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 = {
    newThreadCall
  };

  /**
   * Gets the repositories of the user from Github
   */
  function* newThread(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.newThreadCall(action.formData)
      const thread = yield effects.call(Api.newThreadCall, action.formData);
      yield effects.call(() => {
        // move to threads list
        TopicsListComponent.history.push(`/${action.formData.topic_slug}/${thread.id}/${thread.slug}`);
      }); // yield put(newThreadSuccess(userData))
    } catch (err) {
      // yield put(repoLoadingError(err))
      yield effects.call(() => {
        console.log(err);
      });
    }
  }
  /**
   * Root saga manages watcher lifecycle
   */

  function* newThreadData() {
    // Watches for NEW_Thread 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_THREAD, newThread);
  }

  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 = 'threads';
  const topicsKey = 'topics';
  function NewThreadPage({
    match,
    // loading,
    // error,
    signedInUser,
    // onSubmitForm,
    newThreadActions,
    topicsActions,
    intl,
    topic
  }) {
    index$1.useInjectReducer({
      key,
      reducer: newThreadReducer
    });
    request.useInjectSaga({
      key,
      saga: newThreadData
    });
    index$1.useInjectReducer({
      key: topicsKey,
      reducer: saga.topicsListReducer
    });
    request.useInjectSaga({
      key: topicsKey,
      saga: saga.topicsData
    });
    React.useEffect(() => {
      if (!topic) {
        // load topic if we navigate url by reloading page
        topicsActions.loadTopic(match.params.topicSlug);
      }
    }, []);
    const formList = ['title', 'content'];
    const formDict = formList.reduce((_obj, x) => {
      const obj = Object.assign({}, _obj);
      obj[x] = '';
      return obj;
    }, {
      topic_slug: match.params.topicSlug
    });
    const [formData, setFormData] = React.useState(formDict);
    const [errors, setErrors] = React.useState({}); // const [mdeTab, setMdeTab] = useState('write')

    const [submitDisabled, setSubmitDisabled] = React.useState(true);

    const validateForm = () => {
      const validationErrors = {};
      formList.forEach(function (formKey) {
        if (!formData[formKey]) {
          validationErrors[formKey] = `${formKey} is required`;
        }
      });
      return validationErrors;
    }; // 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
      }));
    };

    const handleContentChange = val => {
      setFormData(prevState => _objectSpread(_objectSpread({}, prevState), {}, {
        content: val
      }));
    };

    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();
      newThreadActions.newThread(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'
        }
      });
    } // const markdownConverter = new Showdown.Converter({
    //   tables: true,
    //   simplifiedAutoLink: true,
    //   strikethrough: true,
    //   tasklists: true,
    // })

    /* 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 Thread"), /*#__PURE__*/React__default['default'].createElement("meta", {
      name: "description",
      content: "React comments django new thread 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.newThreadHeader), " on the", ' ', topic.title)), /*#__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, {
      // label={intl.formatMessage(messages.title)}
      type: "text",
      required: true,
      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.content)), /*#__PURE__*/React__default['default'].createElement(ContentEditor, {
      onContentChange: handleContentChange
    })), /*#__PURE__*/React__default['default'].createElement(Button__default['default'], {
      type: "submit",
      disabled: submitDisabled
    }, /*#__PURE__*/React__default['default'].createElement(reactIntl.FormattedMessage, messages.submitButton))))));
  }
  NewThreadPage.propTypes = {
    newThreadActions: PropTypes__default['default'].shape({
      newThread: PropTypes__default['default'].func.isRequired
    }).isRequired,
    topicsActions: PropTypes__default['default'].shape({
      loadTopic: 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]),
    match: PropTypes__default['default'].object,
    topic: PropTypes__default['default'].oneOfType([PropTypes__default['default'].object, PropTypes__default['default'].bool])
  };
  const mapStateToProps = reselect.createStructuredSelector({
    signedInUser: selectors.makeSelectSignedInUser(),
    topic: saga.makeSelectTopic() // formData: makeSelectFormData(),
    // loading: makeSelectLoading(),
    // error: makeSelectError(),

  });
  function mapDispatchToProps(dispatch) {
    return {
      topicsActions: redux.bindActionCreators(saga.loadTopicsActionsCreator, dispatch),
      newThreadActions: redux.bindActionCreators(newThreadCreators, dispatch)
    };
  }
  const withConnect = reactRedux.connect(mapStateToProps, mapDispatchToProps);
  var index = redux.compose(withConnect, React.memo)(reactIntl.injectIntl(NewThreadPage));

  exports.NewThreadPage = NewThreadPage;
  exports.default = index;
  exports.mapDispatchToProps = mapDispatchToProps;

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