import { h, Component } from 'preact'
import { Link } from 'react-router-dom'

import Modal from '../Modal.jsx'
import FolderForm from './FolderForm.jsx'

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

export default class Folders extends Component {
  constructor(props) {
    super()
    this.state = {
      adding: false,
    }
  }
  openModal() {
    this.setState({ adding: true })
  }
  closeModal() {
    this.setState({ adding: false })
  }
  toggle(folder) {
    folder.open = ! folder.open
    if (folder.open && ! folder.files) {
      client.file.index({ 'folder_id': folder.id }).then( files => {
        console.log(files)
        folder.files = files
        this.props.openFolder(folder)
      })
    }
  }
  render() {
    console.log(this.props)
    const folders = (this.props.folders || []).map( (folder,i) => {
      return (
        <div key={i} onClick={() => this.toggle(folder)}>
          <span class='name'>{folder.name}</span>
        </div>
      )
    })
    return (
      <div class='folders'>
        <div class='heading'>
          <b>folders</b>
          <div class='buttons'>
            <button onClick={() => this.openModal()}>+ folder</button>
          </div>
        </div>
        <div class='list'>
          {folders}
        </div>
        <Modal visible={this.state.adding} onClose={() => this.closeModal()}>
          <FolderForm addFolder={this.props.addFolder} onClose={() => this.closeModal()} />
        </Modal>
      </div>
    )
  }
}
