
var editor;
var server;
var filePath;
var isSave = false;

function onResize() {
  $(".CodeMirror").css("width", (document.documentElement.clientWidth)+"px");
  $(".CodeMirror").css("height", (document.documentElement.clientHeight-32)+"px");
}

$(function() {
  var fileType = getUrlArg("type");
  var mode = "";
  if(fileType=="html" || fileType=="htm") {
    mode = {
      name: "htmlmixed",
      scriptTypes: [{matches: /\/x-handlebars-template|\/x-mustache/i,
                     mode: null},
                    {matches: /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i,
                     mode: "javascript"}]
    };
  } else if(fileType=="js" || fileType=="json") {
    mode = "javascript";
  } else if(fileType=="css") {
    mode = "css";
  }

  var options = {
    mode: mode,
    lineNumbers: true,
    styleActiveLine: true,
    matchBrackets: true,
    selectionPointer: true,
    keyMap: "sublime",
    foldGutter: true,
    autoCloseBrackets: true,
    gutters: ["CodeMirror-lint-markers", "CodeMirror-linenumbers", "CodeMirror-foldgutter"],
    hintOptions: {completeSingle: false}
  };

  if(getUrlArg("readonly")) options.readOnly = true;

  if(fileType=="html" || fileType=="htm") {
    options.matchTags = true;
    options.autoCloseTags = true;
  }

  editor = CodeMirror(document.getElementById("codeEditor"), options);

  $(".CodeMirror").css("width", (document.documentElement.clientWidth)+"px");
  $(".CodeMirror").css("height", (document.documentElement.clientHeight-32)+"px");

  CodeMirror.on(editor, 'change', function(instance, object) {
    var str = object.text[0];
    if(str.length==1 && /^[a-zA-Z.]+$/.test(str) && str!="u" && str!="U") {
      CodeMirror.showHint(editor, CodeMirror.hint.custom);
      //if(str==".") server.complete(editor);
    }
  });

  var codeEditorTheme = localStorage.getItem("codeEditorTheme");
  //if(codeEditorTheme=="monokai") {
    editor.setOption("theme", "monokai");
  //}

  server = new CodeMirror.TernServer({defs: [jsdefs]});
  editor.setOption("extraKeys", {
    "Ctrl-I": function(cm) { server.showType(cm); },
    "Ctrl-O": function(cm) { server.showDocs(cm); },
    "Alt-.": function(cm) { server.jumpToDef(cm); },
    "Alt-,": function(cm) { server.jumpBack(cm); },
    "Ctrl-Q": function(cm) { server.rename(cm); },
    "Ctrl-.": function(cm) { server.selectName(cm); },
    "Ctrl-S": function(cm) { save(); }
  });
  editor.on("cursorActivity", function(cm) { server.updateArgHints(cm); });

  $(".divToolImg").mouseover(function(){
    if($(this).attr("id")=="divToolImg_wrap") {
      var lineWrapping = editor.getOption("lineWrapping");
      if(lineWrapping) return;
    } else if($(this).attr("id")=="divToolImg_keymap" && $("#divKeyMap").is(":visible")) {
      return;
    }
    $(this).css("background-color", "#515151");
    $(this).css("margin", "2px");
    $(this).css("border", "1px solid #999999");
  });

  $(".divToolImg").mouseout(function(){
    if($(this).attr("id")=="divToolImg_wrap") {
      var lineWrapping = editor.getOption("lineWrapping");
      if(lineWrapping) return;
    } else if($(this).attr("id")=="divToolImg_keymap" && $("#divKeyMap").is(":visible")) {
      return;
    }
    $(this).css("background-color", "");
    $(this).css("margin", "3px");
    $(this).css("border", "0");
  });

  //var webContents = remote.getCurrentWebContents();
  //webContents.send("onAddPageFrame", electron.webFrame.routingId);

  //console.log('frameId:'+electron.webFrame.routingId);

  filePath = getUrlArg("path");
  if(filePath.startsWith("/app/")) $("#btnTest").show();
  
  requestByIPC("dev/service/proj/getFileContent", {filePath: filePath}, function(req, res) {
    if(res.code!=0) {
      showErr(res.message);
      return;
    }
    editor.setValue(res.data);
  });
});

function test() {
  openPage("测试后台服务", "taskbuilder-tbs-designer/requester.html?path="+filePath);
}

function comment() {
  var slt = editor.doc.listSelections()[0];
  if(slt.anchor.ch==0&&slt.anchor.line==0&&
    slt.head.ch==0&&slt.head.line==0) return;
  if(slt.anchor.line==slt.head.line) {
    editor.lineComment(slt.head, slt.anchor);
  } else {
    slt.head.ch = 1;
    slt.anchor.ch = editor.doc.getLine(slt.anchor.line).length;
    editor.blockComment(slt.head, slt.anchor);
  }
}

function uncomment() {
  var slt = editor.doc.listSelections()[0];
  if(slt.anchor.ch==0&&slt.anchor.line==0&&
    slt.head.ch==0&&slt.head.line==0) return;
  editor.uncomment(slt.head, slt.anchor);
}

function toggleWrap(div) {
  var lineWrapping = editor.getOption("lineWrapping");
  if(lineWrapping) {
    editor.setOption("lineWrapping", false);
    $(div).css("background-color", "");
    $(div).css("margin", "3px");
    $(div).css("border", "0");
  } else {
    editor.setOption("lineWrapping", true);
    $(div).css("background-color", "#333");
    $(div).css("margin", "2px");
    $(div).css("border", "1px solid #999999");
  }
}

function toggleKeyMapRef(div) {
  if($("#divKeyMap").is(":visible")) {
    $("#divCenter").css("right", "0px");
    $("#divKeyMapTitle").hide();
    $("#divKeyMap").hide();
    $(".CodeMirror").css("width", (document.documentElement.clientWidth)+"px");
    $(div).css("background-color", "");
    $(div).css("margin", "3px");
    $(div).css("border", "0");
  } else {
    $("#divCenter").css("right", "211px");
    $(".CodeMirror").css("width", (document.documentElement.clientWidth-211)+"px");
    $("#divKeyMapTitle").show();
    $("#divKeyMap").show();
    $(div).css("background-color", "#333");
    $(div).css("margin", "2px");
    $(div).css("border", "1px solid #999999");
  }
}

function getSelectedRange() {
  return { from: editor.getCursor(true), to: editor.getCursor(false) };
}

function formatCode() {
  var range = getSelectedRange();
  editor.autoFormatRange(range.from, range.to);
}

function save() {
  if(isSave) {
    showMsg("正在保存，请稍后！");
    return;
  }
  isSave = true;
  requestByIPC(
    "dev/service/proj/saveFileContent", 
    {filePath: filePath, data: editor.getValue()}, function(req, res) {
    isSave = false;
    if(res.code!=0) {
      showErr(res.message);
      return;
    }
    showMsg("保存成功！");
  });
}
