import {connect} from 'react-redux'
import {matchPath} from 'react-router-dom'
import {bindActionCreators} from 'redux'
import Component from './component'
import routes from 'global/constants/routes'
import {getCourse, showAlert, showModal, updateTitle} from 'store/actions'
import {makeGetCourse} from 'store/selectors'

const mapStateToProps = (state, props) => {
    // This is needed because the OnboardManager is rendered as a child of
    // a "match-all" Route. As a result, we need to parse the courseId from
    // the location ourselves.
    const {location} = props
    const match = matchPath(location.pathname, {
        path: `${routes.JOIN_COURSE}/:courseId${routes.ONBOARD}`,
        exact: true,
    })
    const courseId = match?.params.courseId
    const getCourse = makeGetCourse(courseId)

    return {
        course: getCourse(state),
        courseId,
    }
}

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators(
        {
            getCourse,
            showAlert,
            showModal,
            updateTitle,
        },
        dispatch
    )
}

export default connect(mapStateToProps, mapDispatchToProps)(Component)
