(function () {

  const
    transfer = require('transfer')
    , lodash = require('lodash')
    , dbServer = require('db-server')
    , readdir = require('readdir')
    , fs = require('fs')
    , PATH = require('path')
    , uploadTask = require('uploadtask')
    , appCache = require('app-cache')
    , EventEmitter = require('myevents')
    ;

  transfer['window_load.drag'] = (document, global) => {

    document.addEventListener("dragenter", function (e) {
      stopDefaut(e);
    }, false);

    document.addEventListener("dragover", function (e) {
      stopDefaut(e);
    }, false);
    document.addEventListener("dragstart", function (e) {
      stopDefaut(e);
    }, false);

    document.addEventListener("drop", function (e) {
      stopDefaut(e);
      var files = e.dataTransfer.files;
      if (!files || files.length === 0) {
        return EventEmitter.emit('notice_msg', '通知', `未获取到文件，可能该目录权限不足。请重试……`, 'info');
      }
      var locUrl = document.location.hash;
      var urlArr = locUrl.split('/');

      if (urlArr[urlArr.length - 1] == 'index' && urlArr[urlArr.length - 2] == 'storage') {
        var pid = lodash.last(appCache.breadcrumbs).id;
        for (var i = 0; i < files.length; i++) {
          let stat = fs.statSync(files[i].path);
          if (stat.isDirectory()) {
            dbServer.folder.add(files[i].path, pid);
            continue;
          }
          dbServer.upload.add({
            name: PATH.basename(files[i].path),
            extname: PATH.extname(files[i].path),
            size: stat.size,
            mtime: stat.mtime,
            path: files[i].path,
            pid: pid,
            status: 0,
            end_len: 0,
            md5: '',
            url: ''
          });
        }
        EventEmitter.emit('notice_msg', '准备中', `正在准备上传文件！`, 'upload_folder');
        uploadTask.startAll();
        readdir();
        setTimeout(() => { EventEmitter.emit('task_num_change'); });
      } else {
        return false;
      }
    }, false);

    function stopDefaut(e) {
      e.stopPropagation();
      e.preventDefault();
    }
  }
})();