<script>
const iconNameMap = {
  audio: require('./audio.svg'),
  excel: require('./excel.svg'),
  image: require('./image.svg'),
  pdf: require('./pdf.svg'),
  ppt: require('./ppt.svg'),
  text: require('./txt.svg'),
  video: require('./video.svg'),
  word: require('./word.svg'),
  zip: require('./zip.svg')
}

const folderIcon = require('./folder.svg')
const unknowIcon = require('./unknow.svg')

const iconExtMap = {
  txt: iconNameMap.text,
  jpg: iconNameMap.image,
  png: iconNameMap.image,
  jpeg: iconNameMap.image,
  gif: iconNameMap.image,
  zip: iconNameMap.zip,
  rar: iconNameMap.zip,
  '7z': iconNameMap.zip,
  xlsx: iconNameMap.excel,
  xls: iconNameMap.excel,
  doc: iconNameMap.word,
  docx: iconNameMap.word,
  ppt: iconNameMap.ppt,
  pdf: iconNameMap.pdf,
  mp3: iconNameMap.audio,
  mp4: iconNameMap.video,
  wav: iconNameMap.video
}

function getFileExt(fileName) {
  if (!fileName || typeof fileName !== 'string') {
    return
  }
  const extIndex = fileName.lastIndexOf('.')
  if (extIndex < 0) {
    return fileName
  }
  return fileName.substr(extIndex + 1).toLowerCase()
}

export default {
  name: 'UiFileIcon',
  functional: true,
  props: {
    type: {
      type: String,
      default: 'file',
      validator(value) {
        return ['file', 'folder'].includes(value)
      }
    },
    size: {
      type: String,
      default: 'medium',
      validator(value) {
        return ['medium', 'large', 'small'].includes(value)
      }
    },
    name: {
      type: String,
      default: ''
    }
  },
  render(h, c) {
    const { props, data } = c
    let icon = null
    if (props.type === 'folder') {
      icon = folderIcon
    } else if (props.name) {
      const ext = getFileExt(props.name)
      icon = iconExtMap[ext]
    }
    if (!icon) {
      icon = unknowIcon
    }
    let nextClass = ['ui-file-icon', 'ui-file-icon--' + props.size]
    const className = data.staticClass || data.class
    if (className) {
      if (Array.isArray(className)) {
        nextClass = nextClass.concat(className)
      } else {
        nextClass.push(className)
      }
    }
    return h('span', {
      class: nextClass,
      style: {
        'background-image': `url(${icon})`
      }
    })
  }
}
</script>
<style lang="less">
.ui-file-icon {
  display: inline-block;
  background-position: 50% 50%;
  background-size: 100%;
  background-repeat: no-repeat;
}
.ui-file-icon--small{
  width: 32px;
  height: 32px;
}
.ui-file-icon--medium{
  width: 48px;
  height: 48px;
}
.ui-file-icon--large{
  width: 132px;
  height: 132px;
}
</style>
