/**
 * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 of the
 * License.
 *  
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

using Aga.Controls.Tree;

using MySQL.Controls;
using MySQL.Grt;
using MySQL.Utilities;
using MySQL.Workbench;

namespace MySQL.GUI.Workbench
{
	public partial class ModelCatalogForm : TabDocument
	{
		private WbContext wbContext;
		private ModelCatalogTreeModel catalogTreeModel;
		private Point dragStart;

		private ModelCatalogForm()
		{
			InitializeComponent();
		}

		public ModelCatalogForm(WbContext WbContext)
			: this()
		{
			wbContext = WbContext;

      catalogTreeModel = new ModelCatalogTreeModel(catalogTreeView,
                    wbContext.get_catalog_tree(), nodeStateIcon);
      catalogTreeModel.AddColumn(nameNodeControl, 0, false);
      catalogTreeModel.AddColumn(presenceNodeControl, 1, false);
      catalogTreeView.Model = catalogTreeModel;

      UpdateCatalogTree();
      ExpandImportantNodes();
		}

    public void RefreshContents()
    {
      catalogTreeView.Refresh();
    }

		public void UpdateCatalogTree()
		{
      if (wbContext.get_grt_manager().try_soft_lock_globals_tree())
      {
        AgaTreeStateKeeper stateKeeper = new AgaTreeStateKeeper(catalogTreeView);
        try
        {
          if (catalogTreeModel != null)
            catalogTreeModel.RefreshModel();
        }
        finally
        {
          stateKeeper.RestoreStates();
          wbContext.get_grt_manager().soft_unlock_globals_tree();
        }
      }
		}

    public void updateContextMenu(List<NodeId> nodes)
    {
      catalogMenuStrip.Items.Clear();

      List<MySQL.Grt.MenuItem> items = catalogTreeModel.GrtTree.get_popup_items_for_nodes(nodes);
      foreach (MySQL.Grt.MenuItem grtMenuItem in items)
      {
        ToolStripItem item;
        switch (grtMenuItem.get_type())
        {
          case MenuItemType.MenuSeparator:
            item = new ToolStripSeparator();
            break;
          default:
            item = new ToolStripMenuItem(grtMenuItem.get_caption());
            item.Click += new EventHandler(contextMenuClick);
            item.Enabled = grtMenuItem.get_enabled();
            break;
        }
        item.Tag = grtMenuItem.get_name();
        catalogMenuStrip.Items.Add(item);
      }
    }

    void contextMenuClick(object sender, EventArgs e)
    {
      ToolStripMenuItem menuItem = sender as ToolStripMenuItem;

      List<NodeId> nodes = new List<NodeId>();
      GrtTreeNode treeNode = catalogTreeView.SelectedNode.Tag as GrtTreeNode;
      nodes.Add(treeNode.NodeId);
      string command = menuItem.Tag as string;

      if (!catalogTreeModel.GrtTree.activate_popup_item_for_nodes(command, nodes))
      {
        // The backend could not handle the menu command. See if we can make sense of it here.
        if (command == "refereshCatalog")
          UpdateCatalogTree();
      }
    }

    private void ExpandImportantNodes()
    {
      catalogTreeView.Root.Expand();
      foreach (TreeNodeAdv node in catalogTreeView.Root.Children)
      {
        node.Expand();

        foreach (TreeNodeAdv node2 in node.Children)
          node2.Expand();
      }
    }

		private void catalogTreeView_MouseDown(object sender, MouseEventArgs e)
		{
			dragStart = new Point(e.X, e.Y);
		}

		private void catalogTreeView_MouseMove(object sender, MouseEventArgs e)
		{
      if (e.Button == MouseButtons.Left && catalogTreeModel != null)
			{
				if (Math.Abs(dragStart.X - e.X) > 3 || Math.Abs(dragStart.Y - e.Y) > 3)
				{
          if (catalogTreeView.SelectedNodes.Count > 1)
          {
            List<GrtValue> list= new List<GrtValue>();
            foreach (TreeNodeAdv node in catalogTreeView.SelectedNodes)
            {
              GrtValue val = catalogTreeModel.GetNodeGrtValue(node);

              if (val != null)
                list.Add(val);
            }
            if (list.Count > 0)
              DoDragDrop(list, DragDropEffects.Copy);
          }
          else
          {
            GrtValue val = catalogTreeModel.GetNodeGrtValue(catalogTreeView.SelectedNode);

            if (val != null)
              DoDragDrop(val, DragDropEffects.Copy);
          }
				}
			}
		}

    private void catalogMenuStrip_Opening(object sender, CancelEventArgs e)
    {
      List<NodeId> nodes = new List<NodeId>();
      foreach (TreeNodeAdv node in catalogTreeView.SelectedNodes)
      {
        GrtTreeNode treeNode = node.Tag as GrtTreeNode;
        nodes.Add(treeNode.NodeId);
      }
      updateContextMenu(nodes);
    }

	}
}