// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
GE.dataSet = {};

function bmm() {
  this.callbacks = {}; //element: {id : [callbacks, callbacks]}
  this.searchCache = {}; //element: {term : [nodes]}
  this.curSearchTerm = "";//
};

bmm.prototype.init = function(jq){
 this.$ = jq;
}
  /**
   * Loads a subtree of the bookmark tree and returns a {@code cr.Promise} that
   * will be fulfilled when done. This reuses multiple loads so that we do not
   * load the same subtree more than once at the same time.
   * @return {!cr.Promise} The future promise for the load.
   */
bmm.subTreeResult = function(result) {
  bmm.getInstance().subTreeResult_(result);
};

bmm.searchResult = function(result) {
  bmm.getInstance().searchResult_(result);
};

bmm.prototype.searchResult_ = function(result){
  //result = [[item0,item1,item2]]

  if(result.length == 0){
    return;
  }

  $(".search-header").show();
  $("#search_term").text("\"" + this.curSearchTerm + "\"");
  this.curSearchTerm = "";

  var itemList = $(".bookmark-item");
  itemList.remove();
  var items = result[0];
  this.renderItemList(items);
};

bmm.prototype.import = function(){
  chrome.send("bookmarkManagerPrivate.importbmm", []);
};

bmm.prototype.export = function(){
  chrome.send("bookmarkManagerPrivate.exportbmm", []);
};

bmm.prototype.ToggleDirItem = function (treeLinkNode){
  if($(treeLinkNode).hasClass("open")) {
    $(treeLinkNode).removeClass("open");
  }else{
    $(treeLinkNode).addClass("open");
  }
  var tree_item = $(treeLinkNode).parent().parent();
  $($(".tree-children",tree_item)[0]).toggle();
};

bmm.prototype.bindTreeItemEventHandler = function(node){
  $(".tree-row", node).click(function(){
    var id = $(this).parent().attr("id");
    bmm.getInstance().RenderRightItemlist(id.substr(2));
    $(".tree-row").removeClass("select");
    $(this).addClass("select");
  });

  $(".tree-row", node).dblclick(function(){
    var tree_item = $(this).parent();
    var id = $(this).parent().attr("id");
    $(".tree-row").removeClass("select");
    $(this).addClass("select");
    bmm.getInstance().RenderRightItemlist(id.substr(2));

    var treeLinkNode = $($(".tree-links", tree_item)[0]);
    bmm.getInstance().ToggleDirItem(treeLinkNode);
  });

  $(".expand-icon", node).click(function(){
    var treeLinkNode = $(this).parent();
    bmm.getInstance().ToggleDirItem(treeLinkNode);
  });
};

bmm.prototype.search = function(term, callback) {
  if(term =="undefined" || term.length == 0){
    $(".search-header").hide();
    return;
  }

  if(term in this.searchCache){
    this.searchResult_(this.searchCache[term]);
    return;
  }

  this.curSearchTerm = term;
  chrome.send("bookmarkManagerPrivate.search", [term]);
};

bmm.updateSuccess = function(result){
  bmm.getInstance().updateSuccess_(result);
};


bmm.prototype.RenderRightItemlist = function(id){
  var itemList = $(".bookmark-item");
  itemList.remove();
  $(".search-header").hide();
  bmm.getInstance().loadSubtree(id, false, function(id, result){
    if(result == "undefined" || result.length == 0){
      return;
    }
    bmm.getInstance().renderItemList(result[0].children);
  });
};

bmm.createSuccess = function(result){
  bmm.getInstance().createSuccess_(result);
};

bmm.prototype.updateItem = function(id, title, url){
  chrome.send("bookmarkManagerPrivate.update", [id, title, url]);
};

bmm.prototype.createItem = function(parentId, title, url, index){
    var obj ={};
    (typeof parentId != "undefined") && (obj.parentId = parentId);
    (typeof title != "undefined") && (obj.title = title);
    (typeof url != "undefined") && (obj.url = url);
    (typeof index != "undefined") && (obj.index = index);
    chrome.send("bookmarkManagerPrivate.create", [obj]);
}

bmm.prototype.updateSuccess_ = function(result) {
  var id = result.id;
  var url = result.url;
  var title = result.title;
  var node = $("#" + id);
  $("#tl" + id).text(title);

  $(".edit-item", node).hide();
  $(".normal-item", node).show();
  $(".ni-title", node).text(title);
  $(".ni-url", node).text(url);
  $(".ni-url", node).attr("url", url);
};


bmm.prototype.createSuccess_ = function(result) {
    var bmm_item = this.renderItem(result);
    $(".edit-item", bmm_item).show();
    $(".normal-item", bmm_item).hide();
    $("#bmm_item_list").append(bmm_item);
    $(".tf-title", bmm_item).focus();
    var is_folder = (typeof result.url == "undefined");
    if (is_folder){
       //add to dir tree
        var parentId = result.parentId;
        var parentNode = $("#ti"+parentId);
        var tree_node = $("#tmpl_bm_dir_item").tmpl({
          id : result.id,
          pid : result.parentId,
          dirname : result.title
        });
        $.tmpl.complete();

        var parent_padding_left = $(".tree-links", parentNode).css("padding-left");
        parent_padding_left = parent_padding_left.replace(/px/, "");
        var temp = parseInt(parent_padding_left) + 10;
        $(".tree-links", tree_node).css("padding-left", temp.toString() +"px");

        this.bindTreeItemEventHandler(tree_node);
        $(".expand-icon", tree_node).hide();
        $(".tree-children",tree_node).hide();
        $($(".expand-icon", parentNode)[0]).show();
        $($(".tree-children",parentNode)[0]).append(tree_node);
    }
};

bmm.prototype.subTreeResult_ = function(result) {
  if(typeof result.id == "undefined"){
    return;
  }

  var funcs = this.callbacks[result.id];
  var callback = funcs.pop();
  callback(result.id, result.value);
};

bmm.prototype.editItemEnd = function(node){
  var id  = $(node).attr("id");
  var old_title = $(".ni-title", node).text();
  var old_url = $(".ni-url", node).text();
  var title = $(".tf-title", node).val();
  var url = $(".tf-url", node).val();
  if(title != old_title || url != old_url){
    this.updateItem(id, title, url);
  }else{
    $(".edit-item", node).hide();
    $(".normal-item", node).show();
  }
};


bmm.prototype.renderItem = function(item) {
/*
result{
  children : []//object
  dataAdded : xxxxx
  dataGroupModified : xxxxx
  id: "1"
  index : 0
  parentId: "0"
  title: "本地收藏夹"
  url: "xxxx"
}
*/
  var image_url_suffix = "kwe://favicon/size/16@1x/";
  var is_folder = (typeof item.url == "undefined");
  var node = $("#tmpl_bm_item").tmpl({
    id: item.id,
    pid: item.parentId,
    title: item.title,
    title_url : is_folder ? "#" : item.url,
    url: item.url,
    flag: is_folder,
    origin_url: function() {
        return is_folder ? "images/folder-close.png" : image_url_suffix + item.url;
    }
  });
  $.tmpl.complete();

  if(is_folder){
    $(".tf-url",node).hide();
    $(".ni-url", node).hide();
  }
  $(node).bind("keydown",function(e){
    if (e.which == 46){
      var id = $(this).attr("id");
      var recursive = $(this).hasClass("folder");
      bmm.getInstance().removeItem(id, recursive);
      $(this).remove();
    }
  });

  $(".delete-item-btn", node).click(function(){
      var temp = $(this).parent().parent();
      var id =$(temp).attr("id");
      var is_folder = ($(temp).attr("folder") == "true");
      bmm.getInstance().removeItem(id, is_folder);
      $(temp).remove();
  });

  $(".edit-item-btn", node).click(function(){
    var tree_item = $(this).parent().parent();
    $(".normal-item", tree_item).hide();

    $(".edit-item", tree_item).show();
    $(".tf-title", tree_item).focus();
  });

  $(".bookmarksFont", node).dblclick(function(){
    var bmm_item = $(this).parent();
    var flag = $(bmm_item).attr("folder");
    if(flag == "false"){
      var url = $(".tf-url", this).val();
      window.open(url);
    }else if(flag =="true"){
      var id = $(bmm_item).attr("id");
      var tree_item = $("#ti"+id);
      tree_item.parent().show();
      $($(".tree-row", tree_item)[0]).trigger("click");
    }
  });

  $(".edit-item", node).blur(function(e){
      var title = $(".tf-title", this).val();
      var url = $(".tf-url", this).val();
  });

  $(".tf-title", node).blur(function(e){
      var tf_url_iid = $(this).siblings(".tf-url").attr("iid");
      var target_iid = $(e.relatedTarget).attr("iid");
      if(tf_url_iid != target_iid){
          bmm.getInstance().editItemEnd($(this).parent().parent().parent());
      }
  });

  $(".tf-url", node).blur(function(e) {
      var tf_title_iid = $(this).siblings(".tf-title").attr("iid");
      var target_iid = $(e.relatedTarget).attr("iid");
      if(tf_title_iid != target_iid) {
          bmm.getInstance().editItemEnd($(this).parent().parent().parent());
      }
  });

  $(".edit-item", node).bind("keydown",function(e){
    if (e.which == 13){
      bmm.getInstance().editItemEnd($(this).parent().parent());
    }

    if(e.which == 27){
      var old_title = $(".ni-title", $(this).parent()).text();
      var old_url = $(".ni-url", $(this).parent()).text();
      $(".tf-title",this).val(old_title);
      $(".tf-url",this).val(old_url);
      var parent_node = $(this).parent();
      $(".edit-item", parent_node).hide();
      $(".normal-item", parent_node).show();
    }
  });

  return node;
};

bmm.prototype.renderItemList = function(childs){
    for(var i=0; i< childs.length; i++) {
      var item  = childs[i];
      if($("#" + item.id).length > 0){
        continue;
      }

      var node = this.renderItem(item);
      $("#bmm_item_list").append(node);
    }
 };

bmm.prototype.removeItem = function(id, recursive){
  if(recursive){
    //if folder
    var folder_items = $(".tree-item");
    var item = $("#ti"+id, folder_items);
    $(item).remove();
  }

  //if file

  var file_items = $(".bookmark-item");
  var item = $("#"+id, file_items);
  $(item).remove();

  chrome.send("bookmarkManagerPrivate.remove", [id, recursive]);
};

bmm.prototype.loadSubtree = function(id,folder,callback){
   if(typeof this.callbacks[id] == "undefined"){
     this.callbacks[id] = [];
   }

   this.callbacks[id].push(callback);

   chrome.send("bookmarkManagerPrivate.getSubtree", [id, folder]);
};

