package com.dbxml.db.admin.nodes;

/*
 * dbXML - Native XML Database
 * Copyright (C) 1999-2004  The dbXML Group, L.L.C.
 *
 * 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; either version 2
 * of the License, or (at your option) any later version.
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: CollectionNode.java,v 1.8 2004/07/01 02:05:44 bradford Exp $
 */

import com.dbxml.db.admin.Admin;
import com.dbxml.db.admin.AdminConfig;
import com.dbxml.db.admin.DocWrapper;
import com.dbxml.db.client.CollectionClient;
import com.dbxml.db.client.dbXMLClient;
import java.awt.Color;
import java.awt.Font;
import java.util.Stack;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 * CollectionNode
 */

public final class CollectionNode extends AdminNode implements HasCollection, HasChildren, HasMenu, HasStorage {
   private static final Icon CollectionIcon = new ImageIcon(CollectionNode.class.getResource("database_mini.gif"));
   private static final Icon ServerIcon = new ImageIcon(CollectionNode.class.getResource("server_mini.gif"));
   private static final Icon ServerNCIcon = new ImageIcon(CollectionNode.class.getResource("server_nc_mini.gif"));

   public static final int ACTION_CONNECT = 0;
   public static final int ACTION_DISCONNECT = 1;
   public static final int ACTION_DROP = 2;
   public static final int ACTION_DETACH = 3;
   public static final int ACTION_SHUTDOWN = 4;

   private dbXMLClient dbxml;
   private CollectionClient parent;
   private CollectionClient col;
   private String colName;
   private String label;
   private boolean topLevel;
   private boolean connected;
   private Icon ico = CollectionIcon;
   private AdminNode refreshTarget;

   public CollectionNode(dbXMLClient dbxml, String label) {
      super(null);

      topLevel = true;
      this.dbxml = dbxml;
      this.label = label;

      try {
         dbxml.connect();
         col = dbxml.getDatabase();
         connected = true;
         ico = ServerIcon;
      }
      catch ( Exception e ) {
         e.printStackTrace();
         connected = false;
         ico = ServerNCIcon;
      }
   }

   public CollectionNode(AdminNode parentNode, CollectionClient parent, String colName) {
      super(parentNode);

      topLevel = false;
      this.parent = parent;
      this.label = colName;
      this.colName = colName;
      try {
         col = parent.getCollection(colName);
         connected = true;
      }
      catch ( Exception e ) {
         e.printStackTrace();
         connected = false;
      }
   }

   public String getLabel() {
      if ( topLevel )
         return label;
      else {
         try {
            return col.getName();
         }
         catch ( Exception e ) {
            return "";
         }
      }
   }

   public String getTooltip() {
      if ( !connected )
         return "Database not available";
      else {
         try {
            String colName = col.getCanonicalName();
            if ( colName.equals("/system") || colName.startsWith("/system/") )
               return "This is a System Collection.  Be gentle";
         }
         catch ( Exception e ) {
         }
         return super.getTooltip();
      }
   }

   public Font getFont() {
      if ( topLevel )
         return super.getFont();
      else {
         try {
            String colName = col.getCanonicalName();
            if ( colName.equals("/system") || colName.startsWith("/system/") )
               return super.getFont();
         }
         catch ( Exception e ) {
         }
         return super.getFont().deriveFont(Font.BOLD);
      }
   }

   public Color getColor() {
      try {
         String colName = col.getCanonicalName();
         if ( colName.equals("/system") || colName.startsWith("/system/") )
            return Color.RED;
      }
      catch ( Exception e ) {
      }

      return super.getColor();
   }

   public Icon getIcon() {
      return ico;
   }

   public void close() {
      if ( connected )
         connected = false;
   }

   public CollectionClient getCollection() {
      return col;
   }

   public boolean storeDocWrapper(DocWrapper doc) {
      doc.setCollection(col);
      return doc.store();
   }

   public AdminNode getRefreshTarget() {
      return refreshTarget;
   }

   public AdminNode[] getChildren() {
      if ( connected ) {
         AdminNode[] list;
         int offset;
         if ( topLevel ) {
            list = new AdminNode[7];
            offset = 1;
            list[0] = new SecurityNode(this, col);
         }
         else {
            list = new AdminNode[6];
            offset = 0;
         }

         list[0+offset] = new RolesNode(this, col, RoleNode.COLLECTION);
         list[1+offset] = new IndexesNode(this, col);
         list[2+offset] = new ExtensionsNode(this, col);
         list[3+offset] = new TriggersNode(this, col);
         refreshTarget = new DocumentsNode(this, col);
         list[4+offset] = refreshTarget;
         list[5+offset] = new CollectionsNode(this, col);
         return list;
      }
      else
         return new AdminNode[0];
   }

   public String getMenuTitle() {
      if ( topLevel )
         return "Database";
      else
         return "Collection";
   }

   public MenuItem[] getMenu() {
      if ( topLevel ) {
         MenuItem[] menu;
         if ( connected )
            menu = new MenuItem[5];
         else
            menu = new MenuItem[3];

         if ( connected )
            menu[0] = new MenuItem(ACTION_DISCONNECT, "Disconnect Database");
         else
            menu[0] = new MenuItem(ACTION_CONNECT, "Connect Database");

         menu[1] = MenuItem.SEPARATOR;
         menu[2] = new MenuItem(ACTION_DETACH, "Detach Database");

         if ( connected ) {
            menu[3] = MenuItem.SEPARATOR;
            menu[4] = new MenuItem(ACTION_SHUTDOWN, "Shut Down Server");
         }

         return menu;
      }
      else
         return new MenuItem[]{new MenuItem(ACTION_DROP, "Drop Collection")};
   }

   public int menuAction(int action) {
      switch ( action ) {
         case ACTION_CONNECT:
            try {
               dbxml.disconnect();
            }
            catch ( Exception e ) {
            }
            try {
               dbxml.connect();
               col = dbxml.getDatabase();
               connected = true;
               ico = ServerIcon;
            }
            catch ( Exception e ) {
               connected = false;
               ico = ServerNCIcon;
            }
            return REFRESH_SELF;

         case ACTION_DISCONNECT:
            try {
               dbxml.disconnect();
            }
            catch ( Exception e ) {
            }
            connected = false;
            ico = ServerNCIcon;
            return REFRESH_SELF;

         case ACTION_DETACH:
            try {
               AdminConfig cfg = Admin.getInstance().getAdminConfig();
               cfg.removeDriverConfig(label);
               cfg.save();
               return REMOVE_SELF;
            }
            catch ( Exception e ) {
               Admin.getInstance().addMessage(e.getMessage());
            }
            break;

         case ACTION_DROP:
            try {
               String colName = col.getName();
               String title = "Drop Collection";
               String message = "Are you sure you want to drop the\n"
                              + "Collection '"+colName+"'?";
               int res = JOptionPane.showConfirmDialog(Admin.getInstance(), message, title, JOptionPane.YES_NO_OPTION);
               if ( res == JOptionPane.YES_OPTION ) {
                  col.getParentCollection().dropCollection(colName);
                  return REMOVE_SELF;
               }
            }
            catch ( Exception e ) {
               Admin.getInstance().addMessage(e.getMessage());
            }
            break;

         case ACTION_SHUTDOWN:
            try {
               String colName = col.getName();
               String title = "Shut Down Server";
               String message = "Are you sure you want to shut down the\n"
                              + "Server?  Doing so will cause it to become\n"
                              + "completely unavailable, and will require\n"
                              + "a manual restart.";
               int res = JOptionPane.showConfirmDialog(Admin.getInstance(), message, title, JOptionPane.YES_NO_OPTION);
               if ( res != JOptionPane.YES_OPTION )
                  return REFRESH_NONE;

               col.getClient().shutdown(0);

               try {
                  dbxml.disconnect();
               }
               catch ( Exception e ) {
               }
               connected = false;
               ico = ServerNCIcon;
               return REFRESH_SELF;
            }
            catch ( Exception e ) {
               Admin.getInstance().addMessage(e.getMessage());
            }
            break;
      }

      return REFRESH_NONE;
   }

   public String getCanonicalName() {
      Stack s = new Stack();
      try {
         s.push(col.getName());
         CollectionClient c = col;
         while ( true ) {
            c = c.getParentCollection();
            s.push(c.getName());
         }
      }
      catch ( Exception e ) {
      }

      StringBuffer sb = new StringBuffer();
      while ( !s.empty() ) {
         sb.append('/');
         sb.append((String)s.pop());
      }
      return sb.toString();
   }
}

