dojo.provide("parus.catalogActions");

dojo.require("dijit.Tree");
dojo.require("dijit.tree._dndSelector");

dojo.require("parus.database");
dojo.require("parus.catalogNameDialog");
dojo.require("parus.balanceFolderDialog");

if (!parus) parus = {};

if (!parus.catalogActions) dojo.mixin(parus, {
  catalogActions: {}
});


dojo.mixin(parus.catalogActions, {

  listCatalogTree: function(catalogTree) {
    catalogTree.listMode = !catalogTree.listMode;
    if (catalogTree.listMode) catalogTree.checked = [];
    this.refreshCatalogTree(catalogTree);
  },

  expandCatalogTree: function(catalogTree) {

    catalogTree.forAllChildren(
    catalogTree.selectedNode);

  },

  insertCatalog: function(catalogTree) {

    (new parus.catalogNameDialog({
      title: "Добавление каталога",

      onLoad: function() {
        this.catalogNameEdit.attr("value", "Новый каталог");
      },

      onApply: function() {
        var path = catalogTree.path;

        parus.database.execute("insertCatalog", {
          NPRN: catalogTree.model.getIdentity(path[path.length - 1]),
          SNAME: this.catalogNameEdit.value
        }, function(response) {
          var item = catalogTree.selectedNode.item;

          catalogTree.model.newItemCreated(path[path.length - 1], function() {

            var children = catalogTree.model.getChildren(path[path.length - 1], function(children) {
              (new dojo.DeferredList([catalogTree.selectedNode.setChildItems(children), catalogTree._expandNode(catalogTree.selectedNode)])).then(

              function() {
                path.push(parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"));
                catalogTree.set("path", path);
                catalogTree.selectedNode.domNode.scrollIntoView(false);
                catalogTree.onClick();

              })
            });
          });
        });
        return true;
      }

    })).show();

  },

  updateCatalog: function(catalogTree) {

    (new parus.catalogNameDialog({
      title: "Исправление каталога",

      onLoad: function() {
        var path = catalogTree.path;
        this.catalogNameEdit.attr("value", catalogTree.model.getLabel(path[path.length - 1]));
      },

      onApply: function() {
        var path = catalogTree.path;
        var response = parus.database.execute("updateCatalog", {
          NRN: catalogTree.model.getIdentity(path[path.length - 1]),
          SNAME: this.catalogNameEdit.value
        });
        if (!response) return false;

        parus.catalogActions.refreshCatalogTree(catalogTree);
        return true;
      }

    })).show();


  },

  moveCatalog: function(catalogTree, moveCatalogQueryID) {

    var thispath = catalogTree.path;

    (new parus.treeDialog({
      title: "Перемещение каталога",

      model: (dojo.getObject(catalogTree.model.declaredClass, false))({
        queryid: catalogTree.model.queryid,
        onGetConditions: catalogTree.model.onGetConditions
      }),

      onPerform: function(catalog) {

        var response = parus.database.execute(moveCatalogQueryID || "moveCatalog", {
          NRN: catalogTree.model.getIdentity(thispath[thispath.length - 1]),
          NCRN: catalog
        });

        if (!response) return false;
        parus.catalogActions.refreshCatalogTree(catalogTree);

        return true;

      }

    })).show();

  },

  deleteCatalog: function(catalogTree) {

    var path = catalogTree.path;
    var dialog = new parus.confirmationDialog({

      message: "Удалить каталог \"" + catalogTree.model.getLabel(path[path.length - 1]) + "\"?",

      onApply: dojo.hitch(this, function() {

        var response = parus.database.execute("deleteCatalog", {
          NRN: catalogTree.model.getIdentity(path[path.length - 1])
        });

        if (!response) return false;

        path.pop();
        catalogTree.attr("path", path);

        parus.catalogActions.refreshCatalogTree(catalogTree);

        return true;
      })
    });

    dialog.show();

  },

  insertFolder: function(folderTree) {
    var path = folderTree.path;
    var data = parus.xml.fromXml(parus.parus8.rowNodes(parus.database.query("conditionFolderContent", {
      "RN": folderTree.model.getIdentity(path[path.length - 1])
    }))[0]);

    var dialog = new parus.balanceFolderDialog({
      schema: data["XMLSCHEMA"][0],

      onApply: function() {


        var response = parus.database.execute("insertConditionFolder", {
          "PARENT": folderTree.model.getIdentity(path[path.length - 1]),
          "NAME": dialog.nameEdit.attr("value"),
          "NOTE": dialog.noteEdit.value,
          "VALUES": dialog.buildFolder(),
          "QUERY": dialog.customQuery ? dialog.query : null
        });

        if (!response) return false;

        var item = folderTree.selectedNode.item;

        folderTree.model.newItemCreated(path[path.length - 1], function() {

          var children = folderTree.model.getChildren(path[path.length - 1], function(children) {
            (new dojo.DeferredList([folderTree.selectedNode.setChildItems(children), folderTree._expandNode(folderTree.selectedNode)])).then(

            function() {
              path.push(parus.parus8.nodeField(parus.parus8.rowNodes(response)[0], "NRN"));
              folderTree.set("path", path);
              folderTree.selectedNode.domNode.scrollIntoView(false);
              folderTree.onClick();

            })
          });
        });

        return true;
      }

    });
    dialog.show();
  },

  updateFolder: function(folderTree, refreshAction) {

    var path = folderTree.path;
    var data = parus.xml.fromXml(parus.parus8.rowNodes(parus.database.query("conditionFolderContent", {
      "RN": folderTree.model.getIdentity(path[path.length - 1])
    }))[0]);

    var dialog = new parus.balanceFolderDialog({
      schema: data["XMLSCHEMA"][0],
      folder: data["XMLFOLDER"][0],
      query: data["QUERY"] ? data["QUERY"][0]["#text"] : null,
      name: data["NAME"][0]["#text"],
      note: data["NOTE"][0]["#text"] || null,
      customQuery: ((data["CUSTOM_QUERY"][0]["#text"] || null) == "1"),

      onApply: function() {
        var response = parus.database.execute("updateConditionFolder", {
          "RN": folderTree.model.getIdentity(path[path.length - 1]),
          "NAME": dialog.nameEdit.attr("value"),
          "NOTE": dialog.noteEdit.value,
          "VALUES": dialog.buildFolder(),
          "QUERY": dialog.customQuery ? dialog.query : null
        });

        if (!response) return false;

        var def = parus.catalogActions.refreshCatalogTree(folderTree);
        if (def && refreshAction) def.addCallback(function() {
          refreshAction();
        });

        return true;
      }

    });
    dialog.show();
  },

  moveFolder: function(folderTree) {


    var thispath = folderTree.path;

    (new parus.treeDialog({
      title: "Перемещение каталога",

      model: (dojo.getObject(folderTree.model.declaredClass, false))({
        queryid: folderTree.model.queryid,
        onGetConditions: folderTree.model.onGetConditions
      }),

      onPerform: function(catalog) {

        var response = parus.database.execute("moveConditionFolder", {
          NRN: folderTree.model.getIdentity(thispath[thispath.length - 1]),
          NCRN: catalog
        });

        if (!response) return false;
        parus.catalogActions.refreshCatalogTree(folderTree);

        return true;

      }

    })).show();



  },

  deleteFolder: function(folderTree) {

    var path = folderTree.path;
    var dialog = new parus.confirmationDialog({

      message: "Удалить папку \"" + folderTree.model.getLabel(path[path.length - 1]) + "\"?",

      onApply: dojo.hitch(this, function() {

        var response = parus.database.execute("deleteConditionFolder", {
          NRN: folderTree.model.getIdentity(path[path.length - 1])
        });

        if (!response) return false;

        path.pop();
        folderTree.attr("path", path);

        parus.catalogActions.refreshCatalogTree(folderTree);

        return true;
      })
    });

    dialog.show();
  },

  refreshCatalogTree: function(catalogTree) {
    var path = catalogTree.path;

    if (!catalogTree.hiddenMode) catalogTree.model.refresh();

    catalogTree._itemNodesMap = {};
    catalogTree.selectedItems = null;
    catalogTree.selectedItem = null;

    if (catalogTree.dndController && !dojo.isString(catalogTree.dndController)) {
      var controllerClass = catalogTree.dndController.declaredClass;
      catalogTree.dndController.destroy();
      catalogTree.tree.dndController = controllerClass;
    };

    if (catalogTree.rootNode) {
      catalogTree.rootNode.destroyRecursive();
      catalogTree.rootNode = null;
    };

    catalogTree.postMixInProperties();
    catalogTree.postCreate();

    return (catalogTree.hiddenMode) ? null : catalogTree.set("path", path);

  },


  checkChildren: function(catalogTree) {
    var path = catalogTree.path;

    if ((path.length == 1) && !catalogTree.listMode) {
      parus.catalogActions.listCatalogTree(catalogTree);
      return;
    }

    catalogTree.forAllChildren(
    catalogTree.selectedNode, function(node) {
      node.setChecked(true);
    });

  },

  checkPopupMenuItemAction: function(menu, catalogTree) {
    var isSelected = catalogTree.selectedItem;
    var isValid = catalogTree.model.isValid(catalogTree.selectedItem);

    dojo.forEach(menu.getChildren(), function(menuItem) {
      if (menuItem.itemAction) menuItem.attr("disabled", !isSelected || !isValid);

      if (menuItem.toolBarButton) menuItem.toolBarButton.attr("disabled", menuItem.disabled);
    });
  },

  deleteCatalogTreeItem: function(catalogTree, captionPrefix, queryID) {
    var path = catalogTree.path;
    var dialog = new parus.confirmationDialog({

      message: captionPrefix + " \"" + catalogTree.model.getLabel(path[path.length - 1]) + "\"?",

      onApply: dojo.hitch(this, function() {

        var response = parus.database.execute(queryID, {
          NRN: catalogTree.model.getIdentity(path[path.length - 1])
        });

        if (!response) return false;

        path.pop();
        catalogTree.attr("path", path);

        parus.catalogActions.refreshCatalogTree(catalogTree);

        return true;
      })
    });

    dialog.show();
  }

});