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

import Modal from '../Modal.jsx'

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

import FileUploadButton from './FileUploadButton.jsx'

export default class Folder extends Component {
  constructor(props) {
    super()
    this.state = {
      files: props.folder.files || [],
    }
    this.addFiles = this.addFiles.bind(this)
    if (! props.folder.files) {
      client.file.index({ folder_id: props.folder.id }).then( files => this.setState({ files }) )
    }
  }
  addFiles(newFiles) {
    console.log(newFiles)
    if (! newFiles) return
    const files = this.state.files.concat(newFiles).sort( (a,b) => { return b.id - a.id } )
    this.setState({ files })
  }
  render() {
    console.log(this.props)
    const files = (this.state.files).map( (file, i) => {
      if (! file) return
      return (
        <div key={i}>
          <span class='name'>{file.name}</span>
          <span class='mime'>{file.mime}</span>
        </div>
      )
    })
    return (
      <div class='folders'>
        <div class='heading'>
          <b>{this.props.folder.name}</b>
          <div class='buttons'>
            <FileUploadButton folder={this.props.folder} addFiles={this.addFiles} />
            <button onClick={this.props.onClose}>&times;</button>
          </div>
        </div>
        <div class='list'>
          {files}
        </div>
      </div>
    )
  }
}
