import React from 'react';
import _ from 'lodash';
import {Link} from 'react-router';
import {connect} from 'react-redux';
import {
    IconClock,
    IconQrcode,
    IconTag
} from 'trc-client-core/src/components/Icons';
import {STATIC_ASSETS} from 'trc-client-core/src/constants/url';
import {
    E_LEARNING,
    FACE_TO_FACE,
    DOCUMENT
} from 'trc-client-core/src/constants/CourseType';

import AskForm from 'trc-client-core/src/components/AskForm';
import Col from 'trc-client-core/src/components/Col';
import LearningPlanListCurrentParticipant from 'trc-client-core/src/learningPlan/LearningPlanListCurrentParticipant';
import Grid from 'trc-client-core/src/components/Grid';
import Icon from 'trc-client-core/src/components/Icon';
import Markdown from 'trc-client-core/src/components/Markdown';
import Page from 'trc-client-core/src/components/Page';
import PrerequisiteChart from 'trc-client-core/src/components/PrerequisiteChart';
import RegistrationView from 'trc-client-core/src/course/RegistrationView';
import RequestTrainingView from 'trc-client-core/src/course/RequestTrainingView';
import Strings from 'trc-client-core/src/utils/Strings';
import UserStore from 'trc-client-core/src/user/UserStore';
import Widget from 'trc-client-core/src/components/Widget';

import {requestLearningEventCompletion} from 'trc-client-core/src/participant/LearningEventActions';

var CourseView = React.createClass({
    displayName: 'CourseView',
    contextTypes: {
        location: React.PropTypes.object
    },
    isElearning() {
        return this.props.course.get('type') === 'E_LEARNING';
    },
    startComplete(){
        var {course} = this.props;
        this.props.dispatch(requestLearningEventCompletion({participantId: UserStore.get('participantId'),courseCode: course.get('courseCode')})).then(this.afterCompletion)
    },
    afterCompletion(){
        switch (this.props.course.get('type')){
            case 'DOCUMENT':
                var documentUrl = this.props.course.getIn(['documentTag', 'documents', 0, 'url'])
                var url = (documentUrl.indexOf(STATIC_ASSETS) === -1) ? `/upload/view?objectKey=${documentUrl}` : documentUrl;
                window.open(url,'_blank');
                break;
        }
    },
    render() {
        if(!this.props.course) {
            return null;
        }

        var course = this.props.course.toJS();

        return (
            <Page title={course.workshopName} classes={course.stream === 'TECH' ? 'technical' : ''}>
                <div>
                    <Grid>
                        <Col width={7}>
                            <h1>{course.workshopName} <Icon name="print" className="t-muted l-right hide-print" onClick={window.print}/></h1>
                            <Markdown html={course.overview} />
                            {this.renderSegment('learningOutcomes', 'Learning Outcomes')}
                            {this.renderSegment('attendance', 'Who Should Attend?')}
                            {this.renderPrerequisites()}
                            {this.renderGoToContentButton()}
                        </Col>
                        {this.renderSideBar()}
                    </Grid>
                    <div className="margin-top3">
                        {this.renderActions()}
                    </div>
                </div>
            </Page>
        );
    },
    renderSegment(key, title) {
        var segment = this.props.course.toJS()[key];
        if (segment) {
            return <div>
                <h2>{title}</h2>
                <Markdown html={segment} />
            </div>;
        }
    },
    renderSideBar() {
        var course = this.props.course.toJS();
        var iconProps = {
            className: 'l-right',
            size: 'small'
        };
        return (
            <Col width={3}>
                {this.renderCourseTypeDepartment()}
                <Widget className="row-bottom t-capitalize">
                    <Icon size="large" hexCode={course.courseIcon} className="p" />
                    <p>
                        <IconQrcode {...iconProps}/>
                        <strong>Course Code</strong> <br/>{course.courseCode || '-'}
                    </p>
                    <p>
                        <IconClock {...iconProps} />
                        <strong>Course Duration</strong><br/>{course.duration || '-'}
                    </p>
                    <p>
                        <IconTag {...iconProps} />
                        <strong>Course Type</strong><br/>{_.startCase(course.type).toLowerCase() || '-'}
                    </p>
                </Widget>
                {this.renderEditButton()}

                <div className="Section Section-divided">
                    <ul className="IconList IconList-child">
                        <LearningPlanListCurrentParticipant participantId={UserStore.get('participantId')}/>
                    </ul>
                </div>

                <div className="Section Section-divided">
                    {this.renderAdditionalResources()}
                    {this.renderSimilarCourses()}
                    {this.renderParticipantFeedback()}
                </div>

                <AskForm/>
            </Col>
        );
    },
    renderEditButton() {
        if(UserStore.is('ROLE_SUPER_ADMIN')) {
            if(this.props.course.get('id') && this.context.location.pathname.indexOf('/edit') === -1) {
                return <Link to={`/course/${this.props.course.get('courseCode')}/edit`} className="Button Button-edit w100 margin-bottom">Edit Course</Link>;
            }
        }
    },
    renderCourseTypeDepartment() {
        var items = this.props.course.get('departmentCategory').map((value, key) => {
            return <Col key={`department-${key}`}><Widget modifier="tight" color={value}></Widget></Col>;
        });
        return <Grid modifier="flush">{items.toJS()}</Grid>;
    },
    renderAdditionalResources() {
        var course = this.props.course.toJS();
        if(course.additionalResources) {
            return (
                <section>
                    <h3>Additional Resources</h3>
                    <ul className="IconList IconList-child l-row IconList-document">
                        <Markdown html={course.additionalResources} styling={false}/>
                    </ul>
                </section>
            );
        }
    },
    renderSimilarCourses() {
        var course = this.props.course.toJS();
        if(course.similarCourses && this.props.similarCourses.size) {
            let similarCourses = this.props.similarCourses
                .filter(ii => ii)
                .map(cc => {
                    var iconCode = cc.get('courseIcon');
                    if(iconCode && iconCode.length > 2) {
                        iconCode = Strings.fromHexCode(cc.get('courseIcon'));
                    }
                    return <li key={cc.get('courseCode')}>
                        <Link to={`/course/${cc.get('courseCode')}`} data-icon={iconCode}>{cc.get('workshopName')}</Link>
                    </li>;
                })
                .toJS();

            return (
                <section>
                    <h3>Associated Learning</h3>
                    <ul className="IconList IconList-child l-row">{similarCourses}</ul>
                </section>
            );
        }
    },
    renderParticipantFeedback() {
        if(this.props.course) {
            return (
                <section>
                    <em><Markdown html={this.props.course.get('participantFeedBack')}/></em>
                </section>
            );
        }
    },
    renderPrerequisites() {
        var {prerequisite, course} = this.props;
        var  prerequisiteText = course.get('prerequisites');

        if(prerequisite || prerequisiteText) {
            return <div>
                <h2>Pre-requisites</h2>
                {prerequisite ? <PrerequisiteChart prerequisite={prerequisite}/> : null}
                {prerequisiteText ? <Markdown html={prerequisiteText} /> : null}
            </div>
        }
    },
    renderGoToContentButton() {
        var {course} = this.props;

        var buttonProps = {
            className: "Button Button-large margin-top3"
        };

        switch(course.get('type')) {
            case DOCUMENT:
                var documentTag = course.getIn(['documentTag', 'documents'])
                if(documentTag.size !== 0){
                    return <a className="Button Button-large margin-top3" onClick={this.startComplete} >View Document</a>
                } else {
                    return null
                }

            case E_LEARNING:
                var url = course.getIn(['eLearningTag', 'url']) || '';
                if(url.indexOf('lms.toyota.com.au') !== -1) {
                    return <a {...buttonProps} href={url}>Go To Content</a>;
                }
                if(url){
                    return <Link {...buttonProps} to={`/course/${course.get('courseCode')}/launch`}>Go To Content</Link>;
                }

            default:
                return null;
        }
    },
    renderActions() {
        var course = this.props.course.toJS();

        switch(course.type) {
            case FACE_TO_FACE:
                if(UserStore.is('ROLE_MANAGER')) {
                    return <div>
                        <RegistrationView courseCode={course.courseCode} course={this.props.course} courseId={course.id} workshopName={course.workshopName}/>
                    </div>
                }
                return <RequestTrainingView course={this.props.course} courseId={course.id} />;

            default:
                return null;
        }

    }
});

export default  connect(state => ({
    completion: state.completion
}))(CourseView);

