import { store, uploadFile } from '../../reducer/store'

function setHighlightStyle(dropArea) {
  var style = document.createElement('style')

  style.type = 'text/css'
  style.innerHTML = `.highlight_me {
    background: orange;
    cursor: pointer;
  }`

  dropArea.appendChild(style)
}

export default class FileImporter {
  static preview(file) {
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onloadend = function() {
      let preview = document.createElement('img')
      preview.src = reader.result

      preview.style.width = '100%'
      preview.style.height = '100%'
      preview.style.margin = '0'
      preview.style.padding = '0'

      var dialog = document.createElement('paper-dialog')

      dialog.style.width = '100%'
      dialog.style.height = '100%'
      dialog.setAttribute('with-backdrop', true)
      dialog.setAttribute('auto-fit-on-attach', true)
      dialog.setAttribute('always-on-top', true)
      dialog.addEventListener('iron-overlay-closed', () => {
        dialog.parentNode.removeChild(dialog)
      })

      dialog.appendChild(preview)
      document.body.appendChild(dialog)

      requestAnimationFrame(() => {
        dialog.open()
      })
    }
  }

  static async upload(file) {
    store.dispatch(uploadFile(file))
  }

  static set(dropArea, judge) {
    setHighlightStyle(dropArea)

    var preventDefaults = e => {
      if (!judge || judge()) {
        e.preventDefault()
        e.stopPropagation()
      }
    }

    var highlight = e => {
      if (!judge || judge()) {
        dropArea.classList.add('highlight_me')
      }
    }

    var unhighlight = e => {
      if (!judge || judge()) {
        dropArea.classList.remove('highlight_me')
      }
    }

    ;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(event => {
      dropArea.addEventListener(event, preventDefaults, false)
    })
    ;['dragenter', 'dragover'].forEach(event => {
      dropArea.addEventListener(event, highlight, false)
    })
    ;['dragleave', 'drop'].forEach(event => {
      dropArea.addEventListener(event, unhighlight, false)
    })

    dropArea.addEventListener(
      'drop',
      e => {
        if (!judge || judge()) {
          let dt = e.dataTransfer
          let files = dt.files

          // [...files].forEach((file) => FileImporter.preview(file));
          ;[...files].forEach(file => FileImporter.upload(file))
        }
      },
      false
    )
  }
}
