/**
 * Created by DennysO on 6/27/2015.
 */
var AdminStats = React.createClass({
    handleChangePage: function (page, filter) {
        this.setState({curPage: page, filter: filter});
    },
    getInitialState: function () {
        return {curPage: '', filter: ''}
    },
    componentWillUnmount: function () {
        if(!Back)
        {
            Navigation.push("adminStats");
        }
        else
        {
            Back = false;
        }
    },
    render: function () {
        //console.log("filter: ", this.state.filter, "curPage: ", this.state.curPage);
        var result = '';
        switch (this.state.curPage) {
            case 'students':
                result = <AdminStatsStudents filter={this.state.filter} onPageChange={this.handleChangePage}/>;
                break;
            case 'projects':
                result = <AdminStatsProjects onPageChange={this.handleChangePage}/>;
                break;
            case 'grades':
                result = <AdminStatsGrades filter={this.state.filter} onPageChange={this.handleChangePage}/>;
                break;
            default:
                result = <AdminStatsProjects onPageChange={this.handleChangePage}/>;
        }

        return (
            <AdminStatsTabs onPageChange={this.handleChangePage}>
                {result}
            </AdminStatsTabs>
        );
    }
});

var AdminStatsTabs = React.createClass({
    handleClick: function (e) {
        e.preventDefault();
        var page = e.target.id;
        this.props.onPageChange(page, '');
    },
    render: function () {
        return (
            <div className="container">
                <ul className="nav nav-pills mj-pills" role="tablist">
                    <li role="presentation" className="active" onClick={this.handleClick}><a href="#" id="projects"
                                                                                             aria-controls="projects"
                                                                                             role="tab"
                                                                                             data-toggle="tab">Projects</a>
                    </li>
                    <li role="presentation" onClick={this.handleClick}><a href="#" id="students"
                                                                          aria-controls="students" role="tab"
                                                                          data-toggle="tab">Students</a></li>
                    <li role="presentation" onClick={this.handleClick}><a href="#" id="grades" aria-controls="grades"
                                                                          role="tab" data-toggle="tab">Grades</a></li>
                </ul>
                {this.props.children}
            </div>
        );
    }
})

var ProjectTable = {};

var AdminStatsProjects = React.createClass({
    getInitialState: function () {
        return (
        {items: []}
        )
    },
    componentDidMount: function () {
        ProjectsEntity.loadProjects();
        $(ProjectsEntity).on('ProjectsHasChanged', function () {
            this.setState({items: ProjectsEntity.getProjects()});
        }.bind(this));
    },
    componentDidUpdate: function () {
        table = $('#statsProject').DataTable();
    },
    componentWillUnmount: function ()
    {
        table.destroy();
        table = '';
        $(UserEntity).off();
        $(TermEntity).off();
        $(LocationsEntity).off();
        $(ProjectsEntity).off();
        $(RolesEntity).off();
        $(StatesEntity).off();
    },
    handleProjectClick: function (id) {
        ProjectsEntity.loadProjectFilter(id);
        $(ProjectsEntity).on('FilterHasChanged', function () {
            this.props.onPageChange("students", ProjectsEntity.get());
        }.bind(this));
    },
    render: function () {
        var scope = this;
        var items = this.state.items;
        var i = 0;
        return (
            <div className="container">
                <br />
                <table id="statsProject" className="table table-bordered table-striped dt-responsive">
                    <thead>
                    <tr>
                        <td>Project Name</td>
                        <td>Raw</td>
                        <td>Approved</td>
                    </tr>
                    </thead>
                    <tbody>
                    {
                        $.map(items, function (itemData) {
                            return [<AdminStatsProjectsRow onProjectClick={scope.handleProjectClick} key={i++} keyId={i} data={itemData}/>];
                        })
                    }
                    </tbody>
                </table>
            </div>
        )
    }
});

var AdminStatsProjectsRow = React.createClass({
    handleOnClick: function (e) {
        e.preventDefault();
        this.props.onProjectClick(this.state.data.id);
        //console.log(this.state.data);
    },
    getInitialState: function () {
        return {curState: this.props.state, data: this.props.data};
    },
    render: function () {
        var state = this.state.curState == 'selected' ? 'td-primary info' : 'td-primary';
        var data = this.props.data;
        var raw = parseInt(data.raw);
        var acc = parseInt(data.accepted);
        var max = parseInt(data.max);
        var rawlable = getLable(raw, max);
        var acclable = getLable(acc, max);
        var maxlable = getLable(max, max);
        var key = data.name.substring(0, 1) + this.props.keyId;
        return (
            <tr id={key} className="td-primary" onClick={this.handleOnClick} state={this.state.curState}>
                <td>{data.name}</td>
                <td><span className={data.raw == 'Pending' ? "label label-success" : getLable(raw, max)}>{data.raw} / {data.max}</span></td>
                <td><span className={data.accepted == 'Pending' ? "label label-success" : getLable(acc, max)}>{data.accepted} / {data.max}</span></td>
            </tr>
        );
    }
});

var table = '';

var AdminStatsStudents = React.createClass({
    getInitialState: function () {
        return (
        {items: [], filter: [], table: ''}
        )
    },
    componentDidMount: function () {
        ProjectsEntity.loadStudents();
        $(ProjectsEntity).on('StudentsHasChanged', function () {
            //console.log("adding items to the state: ", ProjectsEntity.getStudents());
            this.setState({items: ProjectsEntity.getStudents()});
        }.bind(this))
    },
    componentDidUpdate: function () {
        if(table != '')
        {
            table.destroy();
        }
        table = $('#statsStudents').DataTable();
        //console.log("filtering now");
        table.column(0).search(this.props.filter, true, false, true).draw();
    },
    componentWillUnmount: function ()
    {
        table.destroy();
        table = '';
        $(UserEntity).off();
        $(TermEntity).off();
        $(LocationsEntity).off();
        $(ProjectsEntity).off();
        $(RolesEntity).off();
        $(StatesEntity).off();
    },
    handleStudentsClick: function (name) {
        //console.log("got here");
        this.props.onPageChange("grades", name);
        /*UserEntity.loadGradesFilter(id);
        $(UserEntity).on('FilterHasChanged', function () {
            this.props.onPageChange("students", UserEntity.get());
        }.bind(this));*/
    },
    render: function () {
        var scope = this;
        var items = this.state.items;
        //console.log("Current items being added to the table: ", items);
        var i = 0;
        return (
            <div className="container">
                <br />
                <table id="statsStudents" className="table table-bordered table-striped dt-responsive">
                    <thead>
                    <tr>
                        <td>Student Name</td>
                        <td style={{width: "40%"}}>Project</td>
                        <td>Raw</td>
                        <td>Approved</td>
                    </tr>
                    </thead>
                    <tbody>
                    {
                        $.map(items, function (itemData) {
                            return [<AdminStatsStudentsRow onStudentClick={scope.handleStudentsClick} key={i++} keyId={i} data={itemData}/>];
                        })
                    }
                    </tbody>

                </table>
            </div>
        )
    }
});

var AdminStatsStudentsRow = React.createClass({
    handleNameClick: function (e) {
        e.preventDefault();
        //console.log("got here");
        this.props.onStudentClick(this.state.data.name);
    },
    getInitialState: function () {
        return {curState: this.props.state, data: this.props.data};
    },
    render: function () {
        var state = this.state.curState == 'selected' ? 'td-primary info' : 'td-primary';
        var data = this.props.data;
        var raw = parseInt(data.raw);
        var acc = parseInt(data.accepted);
        var max = parseInt(data.max);
        var rawlable = getLable(raw, max);
        var acclable = getLable(acc, max);
        var key = data.name.substring(0, 1) + this.props.keyId;
        return (
            <tr id={key} onClick={this.handleNameClick} className="td-primary" state={this.state.curState}>
                <td>{data.name}</td>
                <td>{data.project}</td>
                <td><span className={data.raw == 'Pending' ? "label label-success" : getLable(raw, max)}>{data.raw} / {data.max}</span></td>
                <td><span className={data.accepted == 'Pending' ? "label label-success" : getLable(acc, max)}>{data.accepted} / {data.max}</span></td>

            </tr>
        );
    }
});

var AdminStatsGrades = React.createClass({
    getInitialState: function () {
        return (
        {items: []}
        )
    },
    componentDidMount: function () {
        GradeEntity.loadGrades();
        $(GradeEntity).on('GradeHasChanged', function () {
            this.setState({items: GradeEntity.getGrade()});
        }.bind(this))
    },
    handleClick: function (i, e) {
        switch (i) {
            case "export":
                DownloadJSON2CSV(Grades);
        }
    },
    componentDidUpdate: function () {
        if(table != '')
        {
            table.destroy();
        }
        table = $('#statsGrades').DataTable();
        //console.log("filtering now");
        table.column(0).search(this.props.filter, true, false, true).draw();
    },
    componentWillUnmount: function ()
    {
        if(table != '')
        {
            table.destroy();
        }
        table = '';
        $(UserEntity).off();
        $(TermEntity).off();
        $(LocationsEntity).off();
        $(ProjectsEntity).off();
        $(RolesEntity).off();
        $(StatesEntity).off();
        $(GradeEntity).off();
    },
    render: function () {
        var items = this.state.items;
        var i = 0;
        return (
            <div>
                <table className="table table-borderless">
                    <tr>
                        <td style={{textAlign: 'right', verticalAlign: 'bottom'}}>
                            <button type="button" className="btn btn-lightblue"
                                    onClick={this.handleClick.bind(null, "export")}><i
                                className="back-icon glyphicon glyphicon-export" style={{fontSize: '14px'}}></i><span
                                className="hidden-xs"> Export Grades</span></button>
                        </td>
                    </tr>
                </table>

                <table id="statsGrades" className="table table-bordered">
                    <thead>
                    <tr>
                        <td>
                            Student Name
                        </td>
                        <td>
                            Judge Name
                        </td>
                        <td>
                            Grade
                        </td>
                        <th>
                            Accepted
                        </th>
                    </tr>
                    </thead>
                    <tbody>
                    {
                        $.map(items, function (itemData) {
                            if (itemData.value != undefined)
                                return [<AdminStatsGradesRow key={i++} keyId={i} data={itemData}/>];
                            else
                                return "";
                        })
                    }
                    </tbody>
                </table>
            </div>
        );
    }
});

var AdminStatsGradesRow = React.createClass({
    handleOnClick: function (e) {
        e.preventDefault();
        GradeEntity.toggleGrade(this.state.data.id);
        var data = this.state.data;
        var accepted = parseInt(data.accepted);
        switch(accepted)
        {
            case 0:
                data.accepted = 1;
                break;
            case 1:
                data.accepted = 2;
                break;
            case 2:
                data.accepted = 0;
                break;
        }
        this.setState({data: data});
    },
    getInitialState: function () {
        return {data: this.props.data};
    },
    render: function () {
        var data = this.state.data;
        var state = '';
        var accepted = parseInt(data.accepted);
        switch(accepted)
        {
            case 0:
                state = "Not Accepted";
                break;
            case 1:
                state = "Accepted";
                break;
            case 2:
                state = "Rejected";
                break;
        }
        var key = data.fname.substring(0, 1) + this.props.keyId;
        return (
            <tr id={key} className={state} onClick={this.handleOnClick}>
                <td>{data.fname} {data.lname}</td>
                <td>{data.jFirstName} {data.jLastName}</td>
                <td>{data.value}</td>
                <td>{state}</td>
            </tr>
        );
    }
});


function getLable(obj,max) {
    if (obj >= ((3/4)*(max))) {
        return "label label-success";
    }
    else if (obj >= ((2/3)*(max))) {
        return "label label-warning";
    }
    else {
        return "label label-danger";
    }
}

