import * as React from 'react'
import { Tree, Divider } from 'antd'
import DirectoryTree from 'antd/lib/tree/DirectoryTree'

export interface IPageItem {
  path: string
  title: string
  order: number
}

interface IPageNode {
  key: string
  item?: IPageItem
  children: { [k: string]: IPageNode }
}

interface Props {
  pages: IPageItem[]
  current: string
  treeView: string
  onSelectPage: (path: string) => void
}

export default class extends React.Component<Props> {
  render() {
    const { pages, current, treeView } = this.props
    const rootNode = this.createPageTree(pages)

    return (
      <div>
        <DirectoryTree
          showIcon={false}
          defaultExpandAll={true}
          onSelect={this.onSelect}
          selectedKeys={[current]}
        >
          {this.renderTreeNode(rootNode, treeView)}
        </DirectoryTree>
      </div>
    )
  }

  private renderTreeNode = (node: IPageNode, treeView: string = null): any => {
    const childNames: string[] = Object.keys(node.children)

    if (treeView) {
      const treeViewParts = treeView.split(':')
      if (treeViewParts.indexOf(node.key) !== -1 && !childNames.length) {
        return null
      } else if (treeViewParts.indexOf(node.key) !== -1 && childNames.length) {
        return childNames.map(name =>
          this.renderTreeNode(node.children[name], treeView)
        )
      }
    }

    if (childNames.length) {
      return (
        <Tree.TreeNode title={node.key} selectable={false}>
          {childNames.map(name =>
            this.renderTreeNode(node.children[name], treeView)
          )}
        </Tree.TreeNode>
      )
    } else {
      const { title, path } = node.item
      return <Tree.TreeNode title={title} isLeaf key={path} />
    }
  }

  private onSelect = (keys: any[]) => {
    const [path] = keys
    this.props.onSelectPage(path)
  }

  private createPageTree(pages: IPageItem[]): IPageNode {
    const root = { children: {}, key: 'root' } as IPageNode
    let currentNode: IPageNode

    pages.forEach(({ path, title }) => {
      const parts = path.split('/')
      currentNode = root
      parts.forEach((part: string) => {
        if (part === '') return

        if (currentNode.children[part] === undefined) {
          currentNode.children[part] = { children: {}, key: part }
          currentNode = currentNode.children[part]
        } else {
          currentNode = currentNode.children[part]
        }
      })
      currentNode.item = { path, title }
    })

    return root
  }
}
