﻿// Copyright (C) 2007 Xtensive LLC.
// All rights reserved.
// For conditions of distribution and use, see license.
// Created by: Alexander Ilyin
// Created:    2007.09.25

Ext.namespace("Xtensive");
Ext.namespace("Xtensive.TreeViewer");

// cfg
//  target : TreePanel

Xtensive.TreeViewerContextMenu = function(cfg) {
  Xtensive.TreeViewerContextMenu.superclass.constructor.call(this, cfg);
  this.openTaskID = 0;
}

Ext.extend(Xtensive.TreeViewerContextMenu, Ext.menu.Menu, {
  init: function() {
    this.treePanel.on('contextmenu', this.onTreePanelContextMenu, this);
    this.treePanel.on('destroy', this.onTreePanelDestroy, this);
    this.on('itemclick', this.onMenuItemClick, this);
    this.on('destroy', function() { this.destoryed = true }, this);
    var sm = this.treePanel.getSelectionModel();
    sm.on('selectionchange', this.onSelectionChange, this);
  },

  getCurrentNode: function() {
    return this.currentNode;
  },

  onTreePanelContextMenu: function(node, e) {
    this.removeAll();
    var show = false;
    if (node.attributes.menuItems && node.attributes.menuItems.length > 0) {
      for (var i = 0; i < node.attributes.menuItems.length; i++) {
        var cmd = node.attributes.menuItems[i];
        this.addMenuItem({
          text: cmd.text,
          command: cmd.command,
          node: node
        });
        show = true;
      }
    }
    if (node.reload) {
      this.addMenuItem({ text: 'Refresh', id: 'refresh', node: node });
      show = true;
    }
    if (show)
      this.showAt(e.getXY());
  },

  onTreePanelDestroy: function() {
    this.destroy();
  },

  onMenuItemClick: function(menuItem) {
    this.openMenuItem(menuItem);
  },

  openMenuItem: function(menuItem) {
    this.currentNode = menuItem.node;
    if (menuItem.command) {
      menuItem.command.execute();
      return;
    }
    if (menuItem.id == 'refresh')
      menuItem.node.reload();
  },

  onSelectionChange: function(sender, node) {
    this.openTaskID++;
    if (node && node.attributes.openCommand) {
      var openNodeTask = new Xtensive.TreeViewer.OpenNodeTask(node, this);
      openNodeTask.id = this.openTaskID;
      openNodeTask.start();
    }
  }
});

Xtensive.TreeViewer.OpenNodeTask = function(node, contextMenu) {
  this.node = node;
  this.contextMenu = contextMenu;
  this.openNodeDelegate = this.openNode.createDelegate(this);
}

Xtensive.TreeViewer.OpenNodeTask.prototype = {
  start: function() {
    window.setTimeout(this.openNodeDelegate, 500);
  },

  openNode: function() {
    if (this.contextMenu.destoryed)
      return;
    var expired = this.id != this.contextMenu.openTaskID;
    if (expired)
      return;
    this.contextMenu.currentNode = this.node;
    this.node.attributes.openCommand.execute();
  }
}


if (typeof (Sys) !== 'undefined')
  Sys.Application.notifyScriptLoaded();