import { h as history, _ as _defineProperty } from './TopicsListComponent-fa574397.js';
import React, { useState, memo, useEffect } from 'react';
import { Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
import { Helmet } from 'react-helmet';
import { defineMessages, injectIntl, FormattedMessage, FormattedHTMLMessage } from 'react-intl';
import { connect } from 'react-redux';
import { compose, bindActionCreators } from 'redux';
import { createStructuredSelector } from 'reselect';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import { A as API_PREFIX, u as useInjectReducer, H as H2 } from './index-9c274173.js';
import ReactMde from 'react-mde';
import * as Showdown from 'showdown';
import 'react-mde/lib/styles/css/react-mde-all.css';
import { r as request, u as useInjectSaga } from './request-a3c74421.js';
import { m as makeSelectSignedInUser } from './selectors-2f99e0dc.js';
import { m as makeSelectTopic, l as loadTopicsActionsCreator, t as topicsListReducer, a as topicsData } from './saga-f1165c7a.js';
import styled from 'styled-components';
import produce from 'immer';
import { takeLatest, call } from 'redux-saga/effects';
import Cookies from 'js-cookie';
import 'sanitize.css/sanitize.css';
import 'connected-react-router';
import 'redux-saga';
import 'history';
import 'hoist-non-react-statics';
import 'invariant';
import 'lodash';

function ContentEditor(props) {
  const [mdeTab, setMdeTab] = useState('write');
  const [content, setContent] = 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.Converter({
    tables: true,
    simplifiedAutoLink: true,
    strikethrough: true,
    tasklists: true
  });
  return /*#__PURE__*/React.createElement(ReactMde, {
    onChange: handleContentChange,
    value: content,
    onTabChange: handleTabChange,
    selectedTab: mdeTab,
    generateMarkdownPreview: markdown => Promise.resolve(markdownConverter.makeHtml(markdown))
  });
}

ContentEditor.propTypes = {
  // className: PropTypes.string,
  onContentChange: PropTypes.func.isRequired,
  initialValue: PropTypes.string
};

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

const CenteredSection = styled(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 = 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(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.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(`${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 call(Api.newThreadCall, action.formData);
    yield call(() => {
      // move to threads list
      history.push(`/${action.formData.topic_slug}/${thread.id}/${thread.slug}`);
    }); // yield put(newThreadSuccess(userData))
  } catch (err) {
    // yield put(repoLoadingError(err))
    yield 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 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) { _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
}) {
  useInjectReducer({
    key,
    reducer: newThreadReducer
  });
  useInjectSaga({
    key,
    saga: newThreadData
  });
  useInjectReducer({
    key: topicsKey,
    reducer: topicsListReducer
  });
  useInjectSaga({
    key: topicsKey,
    saga: topicsData
  });
  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] = useState(formDict);
  const [errors, setErrors] = useState({}); // const [mdeTab, setMdeTab] = useState('write')

  const [submitDisabled, setSubmitDisabled] = 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
    }));
  };

  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.createElement(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.createElement("article", null, /*#__PURE__*/React.createElement(Helmet, null, /*#__PURE__*/React.createElement("title", null, "New Thread"), /*#__PURE__*/React.createElement("meta", {
    name: "description",
    content: "React comments django new thread page"
  })), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(CenteredSection, null, /*#__PURE__*/React.createElement(H2, null, /*#__PURE__*/React.createElement(FormattedMessage, messages.newThreadHeader), " on the", ' ', topic.title)), /*#__PURE__*/React.createElement(Section, null, /*#__PURE__*/React.createElement(Form, {
    onSubmit: handleSubmit
  }, /*#__PURE__*/React.createElement(Form.Group, null, /*#__PURE__*/React.createElement("label", null, /*#__PURE__*/React.createElement(FormattedHTMLMessage, messages.title)), /*#__PURE__*/React.createElement(Form.Control, {
    // label={intl.formatMessage(messages.title)}
    type: "text",
    required: true,
    value: formData.title,
    onChange: handleChange,
    name: "title"
  })), /*#__PURE__*/React.createElement(Form.Group, null, /*#__PURE__*/React.createElement("label", null, /*#__PURE__*/React.createElement(FormattedHTMLMessage, messages.content)), /*#__PURE__*/React.createElement(ContentEditor, {
    onContentChange: handleContentChange
  })), /*#__PURE__*/React.createElement(Button, {
    type: "submit",
    disabled: submitDisabled
  }, /*#__PURE__*/React.createElement(FormattedMessage, messages.submitButton))))));
}
NewThreadPage.propTypes = {
  newThreadActions: PropTypes.shape({
    newThread: PropTypes.func.isRequired
  }).isRequired,
  topicsActions: PropTypes.shape({
    loadTopic: PropTypes.func.isRequired
  }).isRequired,
  signedInUser: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
  // loading: PropTypes.bool,
  // error: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
  match: PropTypes.object,
  topic: PropTypes.oneOfType([PropTypes.object, PropTypes.bool])
};
const mapStateToProps = createStructuredSelector({
  signedInUser: makeSelectSignedInUser(),
  topic: makeSelectTopic() // formData: makeSelectFormData(),
  // loading: makeSelectLoading(),
  // error: makeSelectError(),

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

export default index;
export { NewThreadPage, mapDispatchToProps };
//# sourceMappingURL=index-41c36ad3.js.map
