import { each, filter, find, union } from 'lodash'
import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'

import * as Actions from 'pubsweet-frontend/src/actions'

import SimpleEditor from './SimpleEditor'

export class SimpleEditorWrapper extends React.Component {
  constructor (props) {
    super(props)

    this.save = this.save.bind(this)
    this.update = this.update.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  componentWillMount () {
    const { getCollections, getFragments } = this.props.actions

    getCollections().then(result => {
      getFragments(result.collections[0])
    })

    const { user } = this.props
    user.roles = this.getRoles()
  }

  save (source, callback) {
    const { book, fragment } = this.props
    const { updateFragment } = this.props.actions

    fragment.source = source
    updateFragment(book, fragment)
  }

  fileUpload (file) {
    const { fileUpload } = this.props.actions
    return fileUpload(file)
  }

  update (newChapter) {
    const { book } = this.props
    const { updateFragment } = this.props.actions
    updateFragment(book, newChapter)
  }

  getRoles () {
    const { user, book } = this.props

    const teams = filter(user.teams, (t) => {
      return t.object.id === book.id
    })

    let roles = []
    const addRole = role => { roles = union(roles, [role]) }

    if (user.admin) addRole('admin')

    each(teams, (team) => {
      const name = team.teamType.name
      const modified = name.trim().toLowerCase().replace(' ', '-')
      addRole(modified)
    })

    return roles
  }

  render () {
    const { book, fragment, history, user } = this.props

    return (
      <SimpleEditor
        book={book}
        fileUpload={this.fileUpload}
        fragment={fragment}
        history={history}
        onSave={this.save}
        update={this.update}
        user={user}
      />
    )
  }
}

SimpleEditorWrapper.propTypes = {
  actions: React.PropTypes.object.isRequired,
  book: React.PropTypes.object.isRequired,
  fragment: React.PropTypes.object,
  history: React.PropTypes.object.isRequired,
  user: React.PropTypes.object.isRequired,
  update: React.PropTypes.func
}

function mapStateToProps (state, ownProps) {
  const bookId = ownProps.params.bookId
  const book = find(state.collections, function (c) {
    return c.id === bookId
  })

  const fragmentId = ownProps.params.fragmentId
  const fragment = state.fragments[fragmentId]

  const user = state.currentUser.user

  return { fragment, book, user }
}

function mapDispatchToProps (dispatch) {
  return {
    actions: bindActionCreators(Actions, dispatch)
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(SimpleEditorWrapper)