/**
 * Created by wyz on 14-7-25.
 */

UM.plugins["dropattachment"] = function (){
  var me = this;
  var insertFile = function (file, editor) {
    //模拟数据
    editor.fireEvent('dropattachment', file);
    console.log(">>>>>>>>>>> drop file >>>>>>>>>>>>>");
  };

  me.addListener('ready', function () {
    $(me.body).on(' drop', function (e) { //paste
      //var range = me.selection.getRange();
      var items = e.type === "paste" ? getPasteFile(e) : getDropFile(e);
      if(items){
        try{
          var file = {};
          for(var i=0; i< items.length; i++){
            if(items[i].getAsFile){
              file = items[i].getAsFile();
              if(file.size > (4 * 1024 * 1024)){
                AlertMessage.show({
                  type: "info",
                  text: "文件最大不得超过4MB!",
                  timeout: 3000
                });
              }else{
                insertFile(file, me);
                console.log("insert called  me: ", me);
              }
            }
          }
        }catch(err) {
          console.log("dropattachment  err: ", err);
        }
      }
    });

    //取消拖放图片时出现的文字光标位置提示
    $(me.body).on('dragover', function (e) {
      console.log(" listener dragover  is called   ! !!");
      if(e.originalEvent.dataTransfer.types[0] == 'Files') {
        e.preventDefault();
      }
    });
  });

  function getPasteFile(event){
    var items = (event.clipboardData || event.originalEvent.clipboardData).items;
    return items ? items:null;
    //return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 ? e.clipboardData.items:null;
  }
  function getDropFile(event){
    return event.originalEvent && event.originalEvent.dataTransfer.items ? event.originalEvent.dataTransfer.items:null;
  }

};

