import { Component } from 'react'
import TreeView from 'react-treeview'
import {FileText, FolderPlus, FolderMinus} from 'react-feather'

// implemented from https://github.com/chenglou/react-treeview
class TreeTest extends Component {

    constructor(props) {
        super(props)
        this.state = {
            collapsedBookkeeping: props.dataSource.map(() => true)
        }

        // Open up the first one when loading the page
        this.state.collapsedBookkeeping[0] = false

        this.handleClick = this.handleClick.bind(this)
        this.handleActivityClick = this.handleActivityClick.bind(this)
    }

    handleClick(i) {
        const [...collapsedBookkeeping] = this.state.collapsedBookkeeping
        collapsedBookkeeping[i] = !collapsedBookkeeping[i]
        this.setState({collapsedBookkeeping})
    }

    handleActivityClick(activity) {
        console.log('activity has been clicked', activity)
        this.props.handleViewActivity(activity)
    }

    collapseAll() {
        this.setState({
            collapsedBookkeeping: this.state.collapsedBookkeeping.map(() => true)
        })
    }

    expandAll() {
        this.setState({
            collapsedBookkeeping: this.state.collapsedBookkeeping.map(() => false)
        })
    }

    render() {
        const collapsedBookkeeping = this.state.collapsedBookkeeping
        const { dataSource } = this.props
        return (
            <div>
                {dataSource.map((node, i) => {
                    const label =
                        <span className="node" onClick={this.handleClick.bind(null, i)}>
                            <span className="folder-icon">
                                {collapsedBookkeeping[i] ? <FolderPlus /> : <FolderMinus />}
                            </span>
                            <span className="folder-label">
                                {node.folderName}
                            </span>
                        </span>
                    return (
                        <TreeView
                            key={`folder-${i}`}
                            nodeLabel={label}
                            collapsed={collapsedBookkeeping[i]}
                            onClick={this.handleClick.bind(null, i)}>
                            {node.activities.map((entry, activityIndex) => {
                                return <div className="info" key={`entry-${entry.name}-${activityIndex}`}>
                                        <span className="activity-icon" onClick={this.handleActivityClick.bind(null, entry)}>
                                            <FileText />
                                        </span>
                                        {entry.title}
                                </div>
                            })}
                        </TreeView>
                    )
                })}
            </div>
        )
    }
}

export default TreeTest
