var localFileIndex = 0;
var localFileDic = {};
var remoteFileIndex = 0;
var remoteFileDic = {};

function selectDir() {
  top.taskBuilder.showDirPicker(function(ret) {
    console.log(ret);
    $("#localDir").val(ret);
    getLocalRootDir();
  });
}

function getLocalRootDir() {
  var dirPath = $("#localDir").val();
  if(dirPath=="") {
    alert("请设置本地路径！");
    return;
  }

  localFileDic[0] = dirPath;
  localFileIndex++;
  getLocalFileList(0);
}

function compare(propertyName) {
  return function (object1, object2) {
    var value1 = object1[propertyName];
    var value2 = object2[propertyName];
    if (value2 < value1) {
      return 1;
    }
    else if (value2 > value1) {
      return -1;
    }
    else {
      return 0;
    }
  }
};

function getLocalFileList(fileIndex) {
  let dirPath = localFileDic[fileIndex];
  $("#localDir").val(dirPath);
  let dirs = [];
  let files = [];
  top.taskBuilder.readDir(dirPath, function(list) {
    var pending = list.length;
    if (list.length==0) {
      showLocalFileList([], []);
      return;
    }
    list.forEach(function(file) {
      var dir = dirPath+"/"+file;
      if(file.type=="dir") {
        dirs.push({type:'dir', name: file.name});
      } else {
        let stat = top.taskBuilder.statFile(dirPath+"/"+file.name);
        files.push({type:'file', name: file.name, size: stat.size, mtime: stat.mtime});
      }
      if (!--pending) {
        dirs.sort(compare("name"));
        files.sort(compare("name"));
        showLocalFileList(dirs, files);
        return;
      }
    });
  });
}

function addLocalNode(obj, localDir) {
  if(obj.type=="dir") {
    let fileId = localFileIndex;
    localFileDic[localFileIndex] = localDir+obj.name;
    localFileIndex++;
    $("#divLocalFileList").append("<div class=\"nodeItem\" ondblclick=\""
      +"getLocalFileList("+fileId+")\" style=\"cursor: pointer;\">"
      +"<img src=\"images/dir.png\" /><div class=\"dirName\" "
      +"title=\""+obj.name+"\">"+obj.name+"</div></div>");
  } else {
    $("#divLocalFileList").append("<div class=\"nodeItem fileNode\">"
      +"<img src=\"images/file.png\" /><input type=\"checkbox\" />"
      +"<div class=\"fileName\" title=\""+obj.name+"\">"+obj.name+"</div>"
      +"<div style=\"float: right; width: 60px; text-align: right;\">"
      +formatFileSize(obj.size)+"</div>"
      +"<div style=\"float: right; width: 100px; text-align: center;\">"
      +(new Date(obj.mtime)).format("MM/dd hh:mm:ss")+"</div></div>");
  }
}

function showLocalFileList(dirs, files) {
  $("#divLocalFileList").empty();
  localFileIndex = 0;
  localFileDic = {};
  let localDir = $("#localDir").val();
  if(localDir.lastIndexOf("\\")!=(localDir.length-1)) localDir += "\\";
  for(var i=0;i<dirs.length;i++) {
    addLocalNode(dirs[i], localDir);
  }
  for(var i=0;i<files.length;i++) {
    addLocalNode(files[i]);
  }
}

function gotoUnderLocalDir() {
  let localDir = $("#localDir").val();
  //如果路径为空
  if(localDir.trim()=="") return;
  if(localDir.lastIndexOf("\\")==(localDir.length-1)) {
    //如果已经是驱动器根目录
    if(localDir.indexOf("\\")==localDir.lastIndexOf("\\")) return;
    localDir = localDir.substr(0, localDir.length-1);
  }
  let arrPath = localDir.split("\\");
  arrPath.pop();
  localDir = arrPath.join("\\");
  if(localDir.endsWith(":")) localDir += "\\";
  $("#localDir").val(localDir);
  getLocalRootDir();
}

function upload() {
  var uploadFiles = [];
  $("#divLocalFileList").find(".fileNode").each(function() {
    if($(this).find("input").get(0).checked) {
      uploadFiles.push($(this).find("div").eq(0).html());
    }
  });
  if(uploadFiles.length==0) {
    alert("请选择要上传的文件！");
    return;
  }
  var args = {
    localDir: $("#localDir").val(),
    remoteDir: $("#remoteDir").val(),
    files: uploadFiles
  };
  openDialog("上传文件", "taskbuilder-file-manager/upload.html", 
    "480px", "220px", JSON.stringify(args), function(ret) {
    $("#divLocalFileList").find("input").each(function() {
      $(this).get(0).checked = false;
    });
    getRemoteRootDir();
  });
};

function download() {
  var localDir = $("#localDir").val();
  if(localDir.trim()=="") {
    alert("请选择本地目录！");
    return;
  }
  var downloadFiles = [];
  $("#divRemoteFileList").find(".fileNode").each(function() {
    if($(this).find("input").get(0).checked) {
      downloadFiles.push($(this).find("div").eq(0).html());
    }
  });
  if(downloadFiles.length==0) {
    alert("请选择要下载的文件！");
    return;
  }
  var args = {
    localDir: localDir,
    remoteDir: $("#remoteDir").val(),
    files: downloadFiles
  };
  openDialog("下载文件", "taskbuilder-file-manager/download.html", 
    "480px", "220px", JSON.stringify(args), function(ret) {
    $("#divRemoteFileList").find("input").each(function() {
      $(this).get(0).checked = false;
    });
    getLocalRootDir();
  });
};

function getRemoteRootDir() {
  var dirPath = $("#remoteDir").val();
  if(dirPath=="") {
    alert("请设置远程路径！");
    return;
  }

  remoteFileDic[0] = dirPath;
  remoteFileIndex++;
  getRemoteFileList(0);
}

function getRemoteFileList(fileIndex) {
  let dirPath = remoteFileDic[fileIndex];
  $("#remoteDir").val(dirPath);
  top.taskBuilder.requestByIPC("dev/service/file/getFileList", {dir: dirPath}, function(req, res) {
    showRemoteFileList(res.dirs, res.files);
  });
}

function addRemoteNode(obj, remoteDir) {
  if(obj.type=="dir") {
    let fileId = remoteFileIndex;
    remoteFileDic[remoteFileIndex] = remoteDir+obj.name;
    remoteFileIndex++;
    $("#divRemoteFileList").append("<div class=\"nodeItem\" ondblclick=\""
      +"getRemoteFileList("+fileId+")\" style=\"cursor: pointer;\">"
      //+"<input type=\"checkbox\" />"
      +"<img src=\"images/dir.png\" /> "
      +"<div class=\"dirName\" title=\""+obj.name+"\">"+obj.name+"</div></div>");
  } else {
    $("#divRemoteFileList").append("<div class=\"nodeItem fileNode\">"
      +"<img src=\"images/file.png\" /><input type=\"checkbox\" />"
      +"<div class=\"fileName\" title=\""+obj.name+"\">"+obj.name+"</div>"
      +"<div style=\"float: right; width: 60px; text-align: right;\">"
      +formatFileSize(obj.size)+"</div>"
      +"<div style=\"float: right; width: 100px; text-align: center;\">"
      +(new Date(obj.mtime)).format("MM/dd hh:mm:ss")+"</div></div>");
  }
}

function showRemoteFileList(dirs, files) {
  $("#divRemoteFileList").empty();
  remoteFileIndex = 0;
  remoteFileDic = {};
  let remoteDir = $("#remoteDir").val();
  if(remoteDir.lastIndexOf("/")!=(remoteDir.length-1)) remoteDir += "/";
  for(var i=0;i<dirs.length;i++) {
    addRemoteNode(dirs[i], remoteDir);
  }
  for(var i=0;i<files.length;i++) {
    addRemoteNode(files[i]);
  }
}

function gotoUnderRemoteDir() {
  let remoteDir = $("#remoteDir").val();
  //如果路径为空
  if(remoteDir.trim()=="" || remoteDir.trim()=="/") return;
  if(remoteDir.lastIndexOf("/")==0) {
    remoteDir = "/";
  } else {
    remoteDir = remoteDir.substr(0, remoteDir.lastIndexOf("/"));
  }
  $("#remoteDir").val(remoteDir);
  getRemoteRootDir();
}

function createRemoteDir() {
  openDialog("新建文件夹", "taskbuilder-file-manager/createDir.html", "320px", "140px", null, function(ret) {
    if(!ret || ret.trim()=="") return;
    let remoteDir = $("#remoteDir").val();
    let dirPath = remoteDir+"/"+ret;
    top.taskBuilder.requestByIPC(
      "dev/service/file/createDir", {dirPath: dirPath}, function(req, res) {
      if(res.code!=0) {
        alert(res.message);
        return;
      }
      getRemoteRootDir();
    });
  });
}

function deleteRemoteFile() {
  var args = {
    dir: $("#remoteDir").val(),
    files: []
  };
  $("#divRemoteFileList").find("input").each(function() {
    if($(this).get(0).checked) {
      args.files.push($(this).parent().find(".fileName").html());
    }
  });
  if(args.files.length==0) {
    alert("请选择要删除的文件！");
    return;
  }
  confirm("确定删除？", function() {
    top.taskBuilder.requestByIPC("dev/service/file/deleteFile", args, function(req, res) {
      getRemoteRootDir();
    });
  });
}

$(function() {
  getRemoteRootDir();
});