text: import React, { Component } from 'react';
  import * as PropTypes from 'prop-types';
  import { Formik, Form, Field } from 'formik';
  import { withStyles } from '@material-ui/core/styles';
  import Drawer from '@material-ui/core/Drawer';
  import Dialog from '@material-ui/core/Dialog';
  import DialogContent from '@material-ui/core/DialogContent';
  import DialogTitle from '@material-ui/core/DialogTitle';
  import DialogActions from '@material-ui/core/DialogActions';
  import Typography from '@material-ui/core/Typography';
  import Button from '@material-ui/core/Button';
  import IconButton from '@material-ui/core/IconButton';
  import Fab from '@material-ui/core/Fab';
  import { Add, Close } from '@material-ui/icons';
  import {
    compose, pipe, pluck, assoc,
  } from 'ramda';
  import * as Yup from 'yup';
  import graphql from 'babel-plugin-relay/macro';
  import { ConnectionHandler } from 'relay-runtime';
  import inject18n from '../../../../components/i18n';
  import { commitMutation } from '../../../../relay/environment';
  import TextField from '../../../../components/TextField';
  import CreatedByField from '../../common/form/CreatedByField';
  import ObjectLabelField from '../../common/form/ObjectLabelField';
  import ObjectMarkingField from '../../common/form/ObjectMarkingField';
  import MarkDownField from '../../../../components/MarkDownField';
  
  const styles = (theme) => ({
    drawerPaper: {
      minHeight: '100vh',
      width: '50%',
      position: 'fixed',
      backgroundColor: theme.palette.navAlt.background,
      transition: theme.transitions.create('width', {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.enteringScreen,
      }),
      padding: 0,
    },
    dialogActions: {
      padding: '0 17px 20px 0',
    },
    createButton: {
      position: 'fixed',
      bottom: 30,
      right: 30,
    },
    createButtonContextual: {
      position: 'fixed',
      bottom: 30,
      right: 30,
      zIndex: 2000,
    },
    buttons: {
      marginTop: 20,
      textAlign: 'right',
    },
    button: {
      marginLeft: theme.spacing(2),
    },
    header: {
      backgroundColor: theme.palette.navAlt.backgroundHeader,
      padding: '20px 20px 20px 60px',
    },
    closeButton: {
      position: 'absolute',
      top: 12,
      left: 5,
    },
    importButton: {
      position: 'absolute',
      top: 15,
      right: 20,
    },
    container: {
      padding: '10px 20px 20px 20px',
    },
  });
  
  const courseOfActionMutation = graphql`
    mutation CourseOfActionCreationMutation($input: CourseOfActionAddInput!) {
      courseOfActionAdd(input: $input) {
        ...CourseOfActionLine_node
      }
    }
  `;
  
  const courseOfActionValidation = (t) => Yup.object().shape({
    name: Yup.string().required(t('This field is required')),
    description: Yup.string()
      .min(3, t('The value is too short'))
      .max(5000, t('The value is too long'))
      .required(t('This field is required')),
  });
  
  const sharedUpdater = (store, userId, paginationOptions, newEdge) => {
    const userProxy = store.get(userId);
    const conn = ConnectionHandler.getConnection(
      userProxy,
      'Pagination_coursesOfAction',
      paginationOptions,
    );
    ConnectionHandler.insertEdgeBefore(conn, newEdge);
  };
  
  class CourseOfActionCreation extends Component {
    constructor(props) {
      super(props);
      this.state = { open: false };
    }
  
    handleOpen() {
      this.setState({ open: true });
    }
  
    handleClose() {
      this.setState({ open: false });
    }
  
    onSubmit(values, { setSubmitting, resetForm }) {
      const finalValues = pipe(
        assoc('createdBy', values.createdBy.value),
        assoc('objectMarking', pluck('value', values.objectMarking)),
        assoc('objectLabel', pluck('value', values.objectLabel)),
      )(values);
      commitMutation({
        mutation: courseOfActionMutation,
        variables: {
          input: finalValues,
        },
        updater: (store) => {
          const payload = store.getRootField('courseOfActionAdd');
          const newEdge = payload.setLinkedRecord(payload, 'node'); // Creation of the pagination container.
          const container = store.getRoot();
          sharedUpdater(
            store,
            container.getDataID(),
            this.props.objectLabel,
            newEdge,
          );
        },
        setSubmitting,
        onCompleted: () => {
          setSubmitting(false);
          resetForm();
          this.handleClose();
        },
      });
    }
  
    onResetClassic() {
      this.handleClose();
    }
  
    onResetContextual() {
      this.handleClose();
    }
  
    renderClassic() {
      const { t, classes } = this.props;
      return (
        <div>
          <Fab
            onClick={this.handleOpen.bind(this)}
            color="secondary"
            aria-label="Add"
            className={classes.createButton}
          >
            <Add />
          </Fab>
          <Drawer
            open={this.state.open}
            anchor="right"
            classes={{ paper: classes.drawerPaper }}
            onClose={this.handleClose.bind(this)}
          >
            <div className={classes.header}>
              <IconButton
                aria-label="Close"
                className={classes.closeButton}
                onClick={this.handleClose.bind(this)}
              >
                <Close fontSize="small" />
              </IconButton>
              <Typography variant="h6">
                {t('Create a course of action')}
              </Typography>
            </div>
            <div className={classes.container}>
              <Formik
                initialValues={{
                  name: '',
                  description: '',
                  createdBy: '',
                  objectMarking: [],
                  objectLabel: [],
                }}
                validationSchema={courseOfActionValidation(t)}
                onSubmit={this.onSubmit.bind(this)}
                onReset={this.onResetClassic.bind(this)}
              >
                {({
                  submitForm,
                  handleReset,
                  isSubmitting,
                  setFieldValue,
                  values,
                }) => (
                  <Form style={{ margin: '20px 0 20px 0' }}>
                    <Field
                      component={TextField}
                      name="name"
                      label={t('Name')}
                      fullWidth={true}
                      detectDuplicate={['Course-Of-Action']}
                    />
                    <Field
                      component={MarkDownField}
                      name="description"
                      label={t('Description')}
                      fullWidth={true}
                      multiline={true}
                      rows="4"
                      style={{ marginTop: 20 }}
                    />
                    <CreatedByField
                      name="createdBy"
                      style={{ marginTop: 20, width: '100%' }}
                      setFieldValue={setFieldValue}
                    />
                    <ObjectLabelField
                      name="objectLabel"
                      style={{ marginTop: 20, width: '100%' }}
                      setFieldValue={setFieldValue}
                      values={values.objectLabel}
                    />
                    <ObjectMarkingField
                      name="objectMarking"
                      style={{ marginTop: 20, width: '100%' }}
                    />
                    <div className={classes.buttons}>
                      <Button
                        variant="contained"
                        onClick={handleReset}
                        disabled={isSubmitting}
                        classes={{ root: classes.button }}
                      >
                        {t('Cancel')}
                      </Button>
                      <Button
                        variant="contained"
                        color="primary"
                        onClick={submitForm}
                        disabled={isSubmitting}
                        classes={{ root: classes.button }}
                      >
                        {t('Create')}
                      </Button>
                    </div>
                  </Form>
                )}
              </Formik>
            </div>
          </Drawer>
        </div>
      );
    }
  
    renderContextual() {
      const {
        t, classes, inputValue, display,
      } = this.props;
      return (
        <div style={{ display: display ? 'block' : 'none' }}>
          <Fab
            onClick={this.handleOpen.bind(this)}
            color="secondary"
            aria-label="Add"
            className={classes.createButtonContextual}
          >
            <Add />
          </Fab>
          <Dialog open={this.state.open} onClose={this.handleClose.bind(this)}>
            <Formik
              initialValues={{
                name: inputValue,
                description: '',
                createdBy: '',
                objectMarking: [],
              }}
              validationSchema={courseOfActionValidation(t)}
              onSubmit={this.onSubmit.bind(this)}
              onReset={this.onResetContextual.bind(this)}
              render={({
                submitForm,
                handleReset,
                isSubmitting,
                setFieldValue,
                values,
              }) => (
                <Form>
                  <DialogTitle>{t('Create a course of action')}</DialogTitle>
                  <DialogContent>
                    <Field
                      component={TextField}
                      name="name"
                      label={t('Name')}
                      fullWidth={true}
                    />
                    <Field
                      component={MarkDownField}
                      name="description"
                      label={t('Description')}
                      fullWidth={true}
                      multiline={true}
                      rows="4"
                      style={{ marginTop: 20 }}
                    />
                    <CreatedByField
                      name="createdBy"
                      style={{ marginTop: 20, width: '100%' }}
                      setFieldValue={setFieldValue}
                    />
                    <ObjectLabelField
                      name="objectLabel"
                      style={{ marginTop: 20, width: '100%' }}
                      setFieldValue={setFieldValue}
                      values={values.objectLabel}
                    />
                    <ObjectMarkingField
                      name="objectMarking"
                      style={{ marginTop: 20, width: '100%' }}
                    />
                  </DialogContent>
                  <DialogActions classes={{ root: classes.dialogActions }}>
                    <Button
                      variant="contained"
                      onClick={handleReset}
                      disabled={isSubmitting}
                      classes={{ root: classes.button }}
                    >
                      {t('Cancel')}
                    </Button>
                    <Button
                      variant="contained"
                      color="primary"
                      onClick={submitForm}
                      disabled={isSubmitting}
                      classes={{ root: classes.button }}
                    >
                      {t('Create')}
                    </Button>
                  </DialogActions>
                </Form>
              )}
            />
          </Dialog>
        </div>
      );
    }
  
    render() {
      const { contextual } = this.props;
      if (contextual) {
        return this.renderContextual();
      }
      return this.renderClassic();
    }
  }
  
  CourseOfActionCreation.propTypes = {
    paginationOptions: PropTypes.object,
    classes: PropTypes.object,
    theme: PropTypes.object,
    t: PropTypes.func,
    contextual: PropTypes.bool,
    display: PropTypes.bool,
    inputValue: PropTypes.string,
  };
  
  export default compose(
    inject18n,
    withStyles(styles, { withTheme: true }),
  )(CourseOfActionCreation);
  