import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import {Navigation, State, Link} from 'react-router';
import {connect} from 'react-redux';

import Table from 'bd-stampy/components/Table';
import Iframe from 'bd-stampy/components/Iframe';
import MarkdownViewer from 'trc-client-core/src/components/Markdown';
import Fullscreen from 'trc-client-core/src/utils/Fullscreen';

import ElearningLaunchConfirm from 'trc-client-core/src/course/ElearningLaunchConfirm';
// import {courseDeleteScormSaveData} from 'trc-client-core/src/course/CourseActions';

var CourseLaunchView = React.createClass({
    displayName: 'CourseLaunchView',
    mixins: [
        require('bd-stampy/mixins/ClassMixin'),
        Navigation,
        State
    ],
    getInitialState() {
        return {
            moduleClosed: false,
            serverDown: false,
            hideConfirmDialogue: false,
            reset: false,
            status: null,
            loaded: false
        };
    },
    componentDidMount() {
        window.addEventListener("message", this.receiveMessage, false);
    },
    receiveMessage(e) {
        var data = JSON.parse(e.data);
        if(data.name === 'status') {
            this.setState({status: data.value});
        }

        if(data.value === 'finish') {
            this.onCloseModule();
        }
    },
    onCloseModule() {
        if (!this.state.serverDown) {
            var iframe = ReactDOM.findDOMNode(this.refs.iframe);
            iframe.src = 'about:blank';
        }
        this.setState({moduleClosed: true});
    },
    onLoadIframe() {
        this.setState({loaded: true});
    },
    onFullscreen() {
        var {iframe} = this.refs;
        if (Fullscreen.enabled) {
            if (Fullscreen.active()) {
                Fullscreen.exit();
                this.setState({fullscreen: false});
            } else {
                Fullscreen.request(iframe);
                this.setState({fullscreen: true});
            }
        }
    },
    onBrowse() {
        this.setState({
            hideConfirmDialogue: true,
            reset: false
        });
    },
    onCommence() {
        this.setState({
            hideConfirmDialogue: true,
            reset: true
        });
    },
    getElearningUrl() {
        var {url} = this.props.course.eLearningTag;
        return (this.state.reset) ? `${url}?reset=true` : url;
    },
    render() {
        var {courseCode} = this.props.course;
        return <div>
            {this.renderContent()}
            <div className="Bar Bar-technical flush height-auto" style={{position: 'fixed', bottom: 0, width: '100%'}}>
                <div className="right padding05">
                    {this.renderStatus()}
                </div>
                <Link className="Button Button-technical height-auto padding" to={`/course/${courseCode}`}>Back to course page</Link>
            </div>
        </div>;
    },
    renderContent() {
        var classes = this.createClassName('Elearning');
        classes.is(this.state.loaded, 'loaded');

        var content = <Iframe className="" ref="iframe" src={this.getElearningUrl()} onLoad={this.onLoadIframe}/>;
        var message = <div className="Elearning_message Animation-ellipsis">Loading...</div>;


        if(this.state.moduleClosed) {
            content = <div className="Elearning_message">You have Closed the module.</div>;
        }

        if(
            this.props.courseParticipation.get('completed') &&
            this.props.courseParticipation.get('history').last().get('process') !== 'IN_PROGRESS' &&
            this.state.hideConfirmDialogue === false
        ) {
            message = null;
            classes.modifier('light');
            content = <ElearningLaunchConfirm
                course={this.props.course}
                onBrowse={this.onBrowse}
                onCommence={this.onCommence}
            />;
        }

        if(this.state.loaded) {
            message = null;
        }

        return (
            <div className={classes.className}>
                {message}
                {content}
            </div>
        );
    },
    renderStatus() {
        //
        // Warning this doesnt use constants as the constants have discrepenices
        // beteen upper and lower case
        //
        if(this.state.status) {
            return <div className="right">
                {this.renderSingleStatus('IN_PROGRESS', this.state.status, 'yellow')}
                {this.renderSingleStatus('COMPLETED', this.state.status, 'green')}
            </div>;
        }
    },
    renderSingleStatus(status, compare, color) {
        var classString = (status === compare) ? 'Badge-' + color : 'Badge-muted';
        return <div className={`Badge ${classString} margin-left05`}>{_.startCase(status.toLowerCase())}</div>;
    },
    renderButtons() {
        var closeButton;

        if(this.props.course.eLearningTag.renderCloseBtn) {
            closeButton = <a className="link margin-right" onClick={this.onCloseModule}>Force Close Module</a>;
        }

        return <span className="margin-top">
            <a onClick={this.onFullscreen} className="link margin-right">View Fullscreen</a>
            {closeButton}
        </span>;
    },
    renderStatusTable() {
        return <Table modifier="data" className="t-muted">
            <tr><td className="w25">Course Code: </td><td>{this.props.course.courseCode}</td></tr>
            <tr><td>Duration: </td><td>{this.props.course.duration}</td></tr>
        </Table>;
    }
});

module.exports = connect(state => ({courseParticipation: state.courseParticipation}))(CourseLaunchView);
