React = require 'react'
utils = require '../utils'
Spinner = React.createFactory(require './spinner')

{div, svg, g, path, text} = React.DOM

###
File Display Props

@props.Request - Class 
  used to make the GET file call

@props.fileToken - String
  file id used to retrieve file info

@props.height - String - default: 50
  height of the icon svg

@props.width - String - default: 40
  width of the icon svg

@props.className - String 
  optional className for div container

@props.fileType - String - default: 'PDF' 
  file type to display on svg 

###

FileDisplay = React.createClass
  
  displayName: 'FileDisplay'

  getInitialState: ->
    fileInfo: null
    loading: not fileInfo?

  getDefaultProps: ->
    {
      height: "50"
      width: "40"
      className: ''
      fileType: 'PDF'
      loading: no
    }

  componentWillReceiveProps: (nextProps) ->
    if @props.fileToken isnt nextProps.fileToken
      @getFileInfo(@setFileInfo)

  componentWillMount: ->
    @setState 
      fileInfo: @getFileInfo(@setFileInfo)

  render: ->
    {width, height, className, fileType} = @props
    {fileInfo, loading} = @state


    div {
      key: 'file-display-container'
      className: className
    }, [
        Spinner {
          key: 'spinner'
          length: 5
          className: 'file-spinner'
        } if loading
        svg { 
          key: 'file-icon'
          className: 'file-icon'
          width: width 
          height: height 
          viewBox: "0 0 55 70"
        }, [
          g {
            key: 'group'
            stroke: "#636363" 
            strokeLinejoin: "round" 
            strokeMiterlimit: "10"
          }, [
            path {
              key: 'paper'
              fill: "#fff" 
              d: "M50 17.9v45.4c0 .9-.8 1.7-1.8 1.7H6.8c-1 0-1.8-.8-1.8-1.7V6.7C5 5.8 5.8 5 6.8 5h29.5L50 17.9z"
            }
            path {
              key: 'tab'
              fill: "#F7F7F7" 
              d: "M50 17.9H38.1c-1 0-1.8-.8-1.8-1.7V5L50 17.9z"
            }
          ]
          text {
            key: 'text'
            transform: "matrix(1.02 0 0 1 9.82 40.821)" 
            fill: "#727272" 
            fontFamily: "'HelveticaNeue'"
            fontSize: "18"
          }, fileType
       ]
      div {
        key: 'file-name'
        className: 'file-name'
      }, fileInfo.fileName
      div {
        key: 'file-size'
        className: 'file-size'
      }, utils.bytesToSize(fileInfo.fileSize, 2)
    ]


  getFileInfo: (cb) ->
    {Request, fileToken} = @props
    new Request
      url: "/files/#{fileToken}/details/"
      method: 'GET'
    .done (res) ->
      cb(res) 

  setFileInfo: (fileInfo) ->
    if fileInfo?
      loading = false
    else
      loading = true
    @setState {
      fileInfo: fileInfo
      loading: loading
    }

module.exports = FileDisplay