import { h, Component } from 'preact'

import Folders from './Folders/Folders.jsx'
import Folder from './Folder/Folder.jsx'

import client from '../../client'

class Browser extends Component {
  constructor(props) {
    super()
    let openFolders = JSON.parse( localStorage['openFolders'] || 'null' )
    this.state = {
      folders: [],
      openFolders: openFolders || [],
    }
    client.folder.index().then( folders => this.setState({ folders }) )
  }
  openFolder(folder) {
    if (this.state.openFolders.indexOf(folder.id) === -1) {
      const newOpenFolders = this.state.openFolders.concat(folder.id)
      localStorage['openFolders'] = JSON.stringify(newOpenFolders)
      this.setState({ openFolders: newOpenFolders })
    }
  }
  closeFolder(folder) {
    const openFolders = this.state.openFolders.filter( folder_id => folder_id !== folder.id )
    localStorage['openFolders'] = JSON.stringify(openFolders)
    this.setState({ openFolders })
  }
  addFolder(folder) {
    this.setState({ folders: this.state.folders.concat([folder]) })
  }
  render() {
    const openFolders = this.state.openFolders.map((folder_id) => {
      const folder_list = this.state.folders.filter(folder => folder.id === folder_id)
      if (! folder_list.length) return
      const folder = folder_list[0]
      return (
        <Folder
          folder={folder}
          onClose={() => this.closeFolder(folder)}
        />
      )
    })
    return (
      <div class='column'>
        <Folders folders={this.state.folders}
          openFolder={(folder) => this.openFolder(folder)}
          addFolder={(folder) => this.addFolder(folder)}
        />
        {openFolders}
      </div>
    )
  }
}

export default Browser
