package com.dbxml.db.client.tools.command;

/*
 * 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: Role.java,v 1.6 2004/02/12 00:17:55 bradford Exp $
 */

import com.dbxml.db.client.CollectionClient;
import com.dbxml.db.client.tools.CommandLine;
import com.dbxml.db.common.security.AccessManagerClient;
import com.dbxml.util.dbXMLException;
import java.io.PrintWriter;

/**
 * Role (ROLE) provides several Role management functions.
 */

public final class Role extends CommandBase {
   private static final String ACTION_ADDUSER = "ADDUSER";
   private static final String ACTION_RMUSER = "RMUSER";
   private static final String ACTION_LSUSER = "LSUSER";

   public void process() throws dbXMLException {
      CollectionClient col = (CollectionClient)cl.getProperty(CommandLine.COLLECTION);
      if ( col == null )
         throw new dbXMLException("Collection context required");

      AccessManagerClient manager = new AccessManagerClient(cl.getClient());
      PrintWriter pw = cl.getWriter();

      String roleID = cl.getNextToken("Role ID");
      String action = cl.getNextToken("Role Action").toUpperCase();

      if ( action.equals(ACTION_ADDUSER) ) {
         String userID = cl.getNextToken("User ID");
         manager.addRoleToUser(userID, roleID);
         pw.println("User '"+userID+"' added to Role '"+roleID+"'");
      }
      else if ( action.equals(ACTION_RMUSER) ) {
         String userID = cl.getNextToken("User ID");
         manager.removeRoleFromUser(userID, roleID);
         pw.println("User '"+userID+"' removed from Role '"+roleID+"'");
      }
      else if ( action.equals(ACTION_LSUSER) ) {
         String[] list = manager.listUsersForRole(roleID);
         int count = 0;
         for ( int i = 0; i < list.length; i++ ) {
            pw.println(list[i]);
            count++;
         }

         if ( cl.isPropertyTrue(CommandLine.TOTALS) ) {
            if ( count > 0 )
               pw.println("-----------------------");
            if ( count != 1 )
               pw.println(count + " Users");
            else
               pw.println(count + " User");
         }
      }
      else
         throw new dbXMLException("Unknown action '"+action+"'");
   }
}

