import React from 'react';
import Reflux from 'reflux';
import StoreMixin from 'reflux-immutable/StoreMixin';
import {State, History} from 'react-router';
import CourseStore from 'trc-client-core/src/course/CourseStore';
import CourseActions from 'trc-client-core/src/course/CourseActions';
import Loader from 'trc-client-core/src/components/Loader';

import Icon from 'trc-client-core/src/components/Icon';
import Pagination from 'bd-stampy/components/Pagination';

function paginate(array, ammount, page) {
    var start = page * ammount;
    var end = start + ammount;

    if(start >= array.size) {
        start = array.size - ammount; 
    }

    return array.slice(start, end);
}

var CourseList = React.createClass({
    displayName: 'CourseList',
    contextTypes: {
        location: React.PropTypes.object
    },
    mixins: [
        State, 
        History,
        StoreMixin,
        Reflux.listenTo(CourseStore, 'onStoreChange')
    ],
    getStoreState() {
        return {
            courses: CourseStore.get('courses')                
        };
    },
    getDefaultProps() {
        return {
            viewableInList: true,
            paginateCount: 15,
            filter: () => true
        };
    },
    componentDidMount() {
        CourseActions.fetchCourses({
            onlyViewable: this.props.viewableInList
        });
    },
    onPagingate(e, page) {
        var routeName = this.props.routes[this.props.routes.length - 1].path;
        this.history.replaceState(null, routeName, {page: page});
    },
    filterDepartments(course) {
        if(this.props.department) {
            return course.get('departmentCategory') && course.get('departmentCategory').contains(this.props.department);
        } else {
            return true;
        }
    },
    render() {
        if(!this.state.courses) {
            return <Loader></Loader>;
        }

        var currentPage = parseInt(this.context.location.query.page, 10) || 0;
        var filtered = this.state.courses
            .filter(this.props.filter)
            .filter(this.filterDepartments);

        return (
            <div>
                <ul className="CourseList">
                    {paginate(filtered, this.props.paginateCount, currentPage).map(this.renderCourses)}
                </ul>
                <Pagination length={filtered.size} ammount={this.props.paginateCount} page={currentPage} onClick={this.onPagingate}/>
            </div>
        );
    },
    renderCourses(course, key) {
        return <li key={key}>
            <a href={`/#/course/${course.get('courseCode')}`}>
                <Icon hexCode={course.get('courseIcon')} className="right"></Icon>
                <div className="hug">{course.get('workshopName')}</div>
                <div className="t-muted">{course.get('duration')}</div>
            </a>
        </li>;
    }
});

module.exports = CourseList;

