
var React = require('react');
var _ = require('lodash');
var moment = require('moment');
var {Link} = require('react-router');

var Table = require('bd-stampy/components/Table');
var Input = require('bd-stampy/components/InputElement');
var Label = require('bd-stampy/components/Label');
var Loader = require('trc-client-core/src/components/Loader');

var Tab = require('bd-stampy/components/Tab');
var TabView = require('bd-stampy/components/TabView');
var TabContent = require('bd-stampy/components/TabContent');
var ToggleGroup = require('trc-client-core/src/components/ToggleGroup');
var UserStore = require('trc-client-core/src/user/UserStore');

var PortalStore = require('../portal/PortalStore');

var departments = [
    {label: 'Sales & Fleet', value: 'sales'},
    {label: 'Parts', value: 'parts'},
    {label: 'Service', value: 'service'},
    {label: 'Technical', value: 'tech'},
    {label: 'Management & Admin', value: 'management'},
    {label: 'Body & Paint', value: 'body_paint'}
];

function tableCells(item, name) {
    var p = item.participantData;
    var cells = {
        Staff: function (){
            return {
                value: <Link className="link" to={`/portal/${p.participantId}`}>{p.firstName + ' ' + p.lastName}</Link>,
                sort: p.firstName + p.lastName,
                width: 15
            };
        },
        Position: function (){
            return {
                value: <span dangerouslySetInnerHTML={{__html: p.jobPositionDesc}}></span>,
                sort: p.jobPositionDesc
            };
        },
        Department: function () {
            if(item.courseMatrix) {
                return {
                    value: <span dangerouslySetInnerHTML={{__html: p.department}}></span>,
                    sort: item.courseMatrix.departmentCategory
                };
            }
        },
        Date: function (){
            return {
                value: item._date,
                sort: Date.parse(item._date),
                filter: item._date,
                width: 15
            };
        },
        Manager: function () {
            return {
                value: item.manager
            };
        },
        Course: function () {
            if (item.soData && item.courseMatrix) {
                return {
                    value: <Link lassName="readmore" to={`/course/${item.soData.soItemCode}`}>{item.courseMatrix.workshopName}</Link>,
                    sort: item.courseMatrix.workshopName,
                    width: 20
                };
            }
        }
    };
    return cells[name]();
}


var TrainingActivitySummary = React.createClass({
    displayName: 'TrainingActivitySummary',
    mixins: [
        require('trc-client-core/src/mixins/CourseMixin')
    ],
    statics: {
        willTransitionTo: function (transition) {
            if((!UserStore.is('ROLE_MANAGER') || UserStore.is('ROLE_SUPER_ADMIN') || UserStore.is('ROLE_MEGA_ADMIN')) && transition.path !== '/unauthorized') {
                transition.redirect('/unauthorized');
            }

            if(UserStore.is('ROLE_TMCA_INTERNAL')) {
                transition.redirect('Portal');
            }
        }
    },
    getInitialState: function () {
        return {
            data: null,
            search: undefined,
            filter: []
        };
    },
    componentDidMount: function () {
        this.fetchData();
    },
    fetchData: function () {
        var _this = this;
        PortalStore.getTrainingActivitySummary().then(function (data){
            _this.setState({data: data});
        });
    },
    getSession: function (id) {
        var data = this.state.data.sessionStatusList[id];
        var facility, soStartDate = '-';

        if(data.latestSOData) {
            facility = data.latestSOData.facility;
            soStartDate = moment(new Date(data.latestSOData.soStartDate)).format('DD MMM YY');
        }

        return {
            sessionExistence: data.sessionExistence,
            facility: facility || '-',
            soStartDate: soStartDate
        };
    },
    onSearch: function (e) {
        this.setState({search: e.target.value});
    },
    onToggleDepartment: function (e, selected) {
        var current = _.compact(_.map(selected.value, function (a, b){
            return (a) ? b : null;
        }));

        if (current) {
            this.setState({filter: current});
        }
    },
    applyFilter: function (data) {
        if (this.state.filter) {
            return _.filter(data, function(row) {
                if (this.state.filter.length && row.courseMatrix) {
                    if(_.intersection(row.courseMatrix.departmentCategory, this.state.filter).length) {
                        return true;
                    } else {
                        return false;
                    }
                }
                return true;
            }, this);
        }
        return data;
    },
    render: function() {
        return (
            <div>
                <h1>Training Activity Summary</h1>
                <div className="row hide-print">
                    <p className="row2 hug-top">Monitor your dealership via the Training Activity Summary to track their future and review their development. </p>
                    <div className="w30 l-right">
                        <Label className="hug-top">Filter By Text</Label>
                        <Input name="search" onChange={this.onSearch} placeholder="Search"></Input>
                    </div>
                    <Label className="hug-top">Filter By Course</Label>
                    <ToggleGroup name="Departments" toggles={departments} value={this.state.filter} onChange={this.onToggleDepartment}/>
                </div>
                {this.renderData()}
            </div>
        );
    },
    renderData: function () {
        if (this.state.data) {
            var d = this.state.data;
            return (
                 <TabView transition={false}>
                     <Tab>Current Enrolments ({d.enrolledList.length})</Tab>
                     <TabContent>{this.renderCurrentErollments(d.enrolledList, 'enrollments')}</TabContent>

                     <Tab>Current Waitlists ({d.waitedList.length})</Tab>
                     <TabContent>{this.renderCurrentErollments(d.waitedList, 'waitlists')}</TabContent>

                     <Tab>Evaluation Requests ({d.evaluationRequests.length})</Tab>
                     <TabContent>{this.renderEvaluations(d.evaluationRequests)}</TabContent>

                     <Tab>Outstanding Requests ({d.requestList.length})</Tab>
                     <TabContent>{this.renderRequestedEnrollments(d.requestList)}</TabContent>
                </TabView>
            );
        } else {
            return <Loader></Loader>;
        }
    },
    renderCurrentErollments: function (data, type) {
        var rows = _.map(this.applyFilter(data), function(item) {
            var session = this.getSession(item.id);
            item._date = session.soStartDate;
            var getCells = _.partial(tableCells, item);
            return {
                _id: item.id,
                Staff: getCells('Staff'),
                Position: getCells('Position'),
                Course: {
                    value: <Link className="readmore" to={"/course/"+item.soData.soItemCode}>{item.courseMatrix.workshopName}</Link>,
                    sort: item.courseMatrix.workshopName
                },
                Date: getCells("Date"),
                Venue: session.facility,
                Status: {
                    value: this.renderStatusText(session, item),
                    sort: item.registrationProcess
                }
            };
        }, this);
        return this.renderTable(rows, "No " + type + " to display.");
    },
    renderEvaluations: function (data) {
        //
        // Requests aren't filtered on account of the backend not providing the data
        //
        var rows = _.map(this.applyFilter(data), function(item) {
            item._date = moment(new Date(item.requestTime)).format('DD MMM YY');
            var getCells = _.partial(tableCells, item);
            return {
                _id: item.id,
                Staff: getCells('Staff'),
                Position: getCells('Position'),
                "Request To": item.requestTo.firstName + ' ' + item.requestTo.lastName,
                Course: {
                    value: <Link className="readmore" to={"/course/"+item.course.courseCode}>{item.course.courseCode}</Link>,
                    sort: item.course.courseCode
                },
                Requested: getCells("Date"),
                " ": <a className="Button" href={"/careerPathway/evaluation/" + item.token}>Download</a>
            };
        }, this);

        return this.renderTable(rows, "No requests to display.");
    },
    renderRequestedEnrollments: function (data) {
        var rows = _.map(this.applyFilter(data), function(item) {
            var session = this.getSession(item.id);
            item._date = session.soStartDate;
            var getCells = _.partial(tableCells, item);
            return {
                _id: item.id,
                Staff:      getCells('Staff'),
                Position:   getCells('Position'),
                Course:     getCells('Course'),
                Requested:  getCells("Date"),
                Venue:      session.facility,
                " ": (
                    <div>
                        <a className="w100 Button Button-small" href={"/admin/request-training-in-site/approve?rid=" + item.id}>enrol</a>
                        <a className="w100 Button Button-small Button-grey" href={"/admin/request-training-in-site/deny?rid=" + item.id}>deny</a>
                    </div>)
            };
        }, this);

        return this.renderTable(rows, "No requests to display.");
    },
    renderStatusText: function (session, item) {
        var status = this.getPrettyStatus(item.registrationProcess);
        if (session.sessionExistence === 'EXIST') {
            return <span className={'t-' + status.toLowerCase()}>{status}</span>;
        }
        return <span>Cancelled <small>(SESSION NO LONGER AVAILABLE)</small></span>;
    },
    renderTable: function(rows, emptyText) {
        var empty = <em className="InfoBox">{emptyText}</em>;
        return (
            <Table type="data" modifier="data" search={this.state.search} empty={empty}>{rows}</Table>
        );
    }
});

module.exports = TrainingActivitySummary;
