import React from 'react'
import {doAction} from './api'
import _ from 'lodash/fp'
import {connect} from 'react-redux'

const handleResponse = target => {
  const responseHeader = target.getResponseHeader('Content-Type') || 'Error'
  return responseHeader.includes('application/json')
    ? JSON.parse(target.responseText)
    : responseHeader
}


@connect(_.pick('resources'))
export default class Resources extends React.Component {
  state = {
    status: ''
  }

  handleUpload = async (event) => {
    const file = _.head(event.target.files)
    if (!file) {
      return
    }
    const {blockId} = this.props
    const {data: token} = await doAction('getToken')
    const host = await doAction('getHost')
    const url = `${host}/api/block/${blockId}/resource`
    const {data} = await this.upload({file, url, token})
    const resources = data.reduce((acc, {alias, ref, ...rest}) => {
      acc[ref] = {...alias, ref, ...rest}
      return acc
    }, {})
    const {dispatch} = this.props
    dispatch({type: 'ADD_RESOURCE', payload: resources})
    setTimeout(() => this.setState({status: ''}), 2000)
  }

  handleRemove = ({id, ref}) => async () => {
    const {blockId, dispatch} = this.props
    await doAction('resourceRemove', {ownerId: blockId, id})
    dispatch({type: 'REMOVE_RESOURCE', ref})
  }

  upload = ({file, url, token}) => new Promise((resolve, reject) => {
    this.setState({status: 'Loading'})
    const xhr = new XMLHttpRequest()
    const formData = new FormData()
    xhr.onload = event => {
      if (event.target.status === 201) {
        const response = handleResponse(event.target)
        this.setState({status: 'Finished'})
        resolve(response)
      } else {
        const error = new Error('Error while uploading')
        error.status = handleResponse(event.target)
        this.setState({error: true})
        reject(error)
      }
    }
    xhr.onerror = event => {
      const error = new Error('Error while uploading')
      error.status = handleResponse(event.target)
      this.setState({error: true})
      reject(error)
    }
    xhr.open('POST', url, true)
    xhr.setRequestHeader('Authorization', `Bearer ${token}`)

    formData.append(file.name, file)
    xhr.send(formData)
  })

  render() {
    const {error, status} = this.state
    const {resources} = this.props
    return (
      <div>
        {error ? <div>Error</div> : status}
        <input type="file" accept=".jpg, .png" id="upload" onChange={this.handleUpload} />
        <div className="gallery">
          {_.flow(
            _.entries,
            _.map(([, value]) => {
              const {url, name, _id, ref} = value
              return (
                <div className="picture" key={_id}>
                  <img className="picture__img" src={url}/>
                  <div className="picture__id">{ref}</div>
                  <div onClick={this.handleRemove({ref, id: _id})}>REMOVE</div>
                  <div className="picture__name">{name}</div>
                </div>)
            })
          )(resources)}
        </div>
      </div>
    )
  }
}
