import React from 'react';
import {connect} from 'react-redux';
import UserStore from 'trc-client-core/src/user/UserStore';
import {gapReportRequest} from 'trc-client-core/src/report/ReportActions';
import {requestCertificationCompletion} from 'trc-client-core/src/learningPlan/LearningPlanActions';
import AutoRequest from 'trc-client-core/src/components/AutoRequest';
import Loader from 'trc-client-core/src/components/Loader';
import ErrorMessage from 'trc-client-core/src/components/ErrorMessage';

function getLearningPlanId(props) {
    return props.params.learningPlanId || props.children.props.route.path
}

var LearningPlanHandler = React.createClass({
    displayName: 'LearningPlanHandler',
    render() {
        var {children, learningPlan} = this.props;

        if(!learningPlan) {
            return <Loader/>;
        }

        if(!learningPlan.getIn(['pathwayCompletion', 0])) {
            return <ErrorMessage code={404}/>;
        }

        return (
            <div>
                {React.cloneElement(children, {
                    learningPlan: learningPlan,
                    learningPlanId: getLearningPlanId(this.props),
                    participant: learningPlan.getIn(['pathwayCompletion', 0])
                })}
            </div>
        );
    }
});

const autoRequest = AutoRequest(['params.learningPlanId', 'location.query.participantId'], (props) => {
    var query = {
        pathwayId: getLearningPlanId(props),
        participantId: props.location.query.participantId ? props.location.query.participantId : UserStore.get('participantId'),
        dealerCode: props.location.query.dealerCode || UserStore.get('currentBranchCode')
    };
    props.dispatch(gapReportRequest(query))
    props.dispatch(requestCertificationCompletion(query));
});

const connectWithLearningPlan = connect((state, props) => {
    return {
        learningPlan: state.gapReport.get(getLearningPlanId(props)),
        error: state.gapReport.get('error')
    }
})


export default connectWithLearningPlan(autoRequest(LearningPlanHandler));
