import React, {Component, PropTypes} from 'react';
import {getUser} from '../actions/users';
import {dateDiffToday} from '../utils/general';
import {connect} from 'react-redux';
import {requestUpdate} from '../actions/projects';


class ProjectItem extends Component {
    constructor(props, context) {
        super(props, context);

        this.state = {
            expanded: false
        };
        this.toggleExpanded = this.toggleExpanded.bind(this);
        this.getStatusUser = this.getStatusUser.bind(this);
        this.getClass = this.getClass.bind(this);
        this.getDueDate = this.getDueDate.bind(this);
        this.getDueDateClass = this.getDueDateClass.bind(this);
        this.getPercentCompletedByMilestone = this.getPercentCompletedByMilestone.bind(this);
        this.getCurrentMilestoneName = this.getCurrentMilestoneName.bind(this);
        this.getUser = this.getUser.bind(this);
        this.getStatusUser = this.getStatusUser.bind(this);
        this.getStatusDate = this.getStatusDate.bind(this);
        this.requestStatusUpdate = this.requestStatusUpdate.bind(this);
    }

    getClass(project) {
        let cls = 'project-detail';
        if (project.current_status && project.current_status.color) {
            cls += " status-" + project.current_status.color;
        } else {
            cls += " no-status";
        }
        return cls;
    }

    toggleExpanded() {
        this.setState({expanded: !this.state.expanded});
    }

    getDueDate(project) {
        return (project.due_date) ? project.due_date : "Date not set";
    }

    getDueDateClass(project) {
        let cls = "due-date";
        if (project.due_date) {
            let diff = dateDiffToday(project.due_date);
            if (diff <= 0) {
                cls += ' due-date-danger';
            } else if (diff < 7) {
                cls += ' due-date-warning';
            }
        }
        return cls;
    }

    getPercentCompletedByMilestone() {
        let current = this.props.project.detail.current.milestone;
        let milestones = this.props.project.detail.milestones;
        return "calc( " + ( ( (milestones.indexOf(current) + 1) / milestones.length ) * 100) + "% - 2px)";
    }

    getCurrentMilestoneName() {
        let current = this.props.project.detail.current.milestone;
        if (current && current != "") {
            return this.props.project.detail.current.milestone.slice(0, -1);
        }
        return "...";
    }

    getUser() {
        if (!this.props.project.detail.current.task) {
            return "...";
        } else {
            let assignee = this.props.project.detail.current.task.assignee;
            if (assignee && assignee.id) {
                let taskUser = this.props.users.filter((user) => {
                    return user.id == assignee.id
                });
                if (taskUser.length > 0) {
                    return taskUser[0].name;
                } else {
                    return "...";
                }
            } else {
                return "Unassigned";
            }
        }
    }

    getStatusUser() {

        if (!this.props.project.current_status) {
            return "...";
        } else {
            let author = this.props.project.current_status.author;
            if (author && author.id) {
                let taskUser = this.props.users.filter((user) => {
                    return user.id == author.id
                });
                if (taskUser.length > 0) {
                    return taskUser[0].name;
                } else {
                    this.props.dispatch(getUser(this.props.connection, author.id));
                    return "...";
                }
            } else {
                return "Unassigned";
            }
        }
    }

    getStatusDate(dateO) {
        if (dateO && dateO.modified_at) {
            let d = new Date(dateO.modified_at);
            return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
        }
        return '...';
    }

    requestStatusUpdate() {
        if (this.props.project.detail.current && this.props.project.detail.current.task) {
            this.props.dispatch(requestUpdate(this.props.connection, this.props.project.detail.current.task.id));
        }
    }

    render() {
        return (
            <div className={this.getClass(this.props.project)} aria-expanded={this.state.expanded}>
                <div className="card-block">
                    <h4 className="card-title">
                        <span className="title">{this.props.project.name}</span>
                        <span className={this.getDueDateClass(this.props.project)}>{this.getDueDate(this.props.project)}</span>
                        <button className="btn-expand-card" onClick={this.toggleExpanded} aria-pressed={this.state.expanded}>
                            <svg>
                                <use xlinkHref="#icon-chevron-down"></use>
                            </svg>
                        </button>
                    </h4>
                    <div className="project-progress">
                        <div className="progress-title">Progress</div>
                        <div className="progress-bar">
                            <div className="indicator" style={{width: this.getPercentCompletedByMilestone()}}>
                                {this.getCurrentMilestoneName()}
                            </div>
                            <div className="milestones">
                                {
                                    this.props.project.detail.milestones.map((milestone, index) => {
                                        return
                                        <span className="mile-marker" style={{width: ((100 / this.props.project.detail.milestones.length)) + "%"}} data-name={milestone.slice(0, -1)}>&nbsp;</span>
                                    })
                                }
                            </div>
                        </div>
                    </div>
                    <div className="project-task">
                        <div className="task-title">Current Task:</div>
                        <div className="task-group">
                            <span className="task-group-user">{this.getUser()}</span>
                            <div type="text" className="task-group-task">
                                { this.props.project.detail.current.task ? this.props.project.detail.current.task.name : "..."}
                            </div>
                        </div>
                    </div>
                    <div className="expanded-detail">
                        <div className="status">
                            {(this.props.project.current_status) &&
                            (<div className="status-info">
                                    <span className="status-author">Updated by {this.getStatusUser()}</span>
                                    <span className="status-date"> at {this.getStatusDate(this.props.project.current_status)} </span>
                                </div>)
                            }

                            <div className="status-text">{this.props.project.current_status ? this.props.project.current_status.text : 'No Update Present'}</div>
                        </div>
                        <div className="status-actions">
                            <button className="btn-request-task-update" onClick={this.requestStatusUpdate} data-busy={this.props.busy}>
                                Request Task Update
                                <svg className="spinner" width="18px" height="18px" viewBox="0 0 66 66" xmlns="http://www.w3.org/2000/svg">
                                    <circle className="path" fill="none" strokeWidth="6" strokeLinecap="round" cx="33" cy="33" r="30"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

ProjectItem.propTypes = {
    project: PropTypes.object.isRequired
};

function mapStateToProps(state) {
    "use strict";

    return {
        users: state.users,
        connection: state.connection,
        busy: state.busy > 0
    }
}

export default connect(mapStateToProps)(ProjectItem);