#!/usr/bin/perl

use strict;

use lib '/app/tools/common/lib';
use Common::DB::Item::Permission;
use Common::DB::Item::AccessLevel;
use Common::RSDB;
use Common::RSApp;


addCommand();



sub output
{
	my $string = shift;

	print "$string\n";
}

sub addCommand
{
	# Instantiate the application singleton object.
	#
	my $appSingleton = Common::RSApp->new(clientID => 1);

	my $coll = Common::DB::Item::AccessLevel->GetAll();
	my %accessLevels;
	while($coll->hasNext())
	{
		my $item = $coll->next();
		$accessLevels{$item->access_level_id()} = $item->name();
	}

	if(! keys %accessLevels)
	{
		return usage("Woops! No access levels found in the database.");
	}

	my $app;
	my $area;
	my $command;
	my $newPermission;

	COMMAND:
	output("Create new command...\n");
	$app = getInput("Enter application (eg. rps): ");
	$area = getInput("Enter area (eg. catalog): ");
	$command = getInput("Enter command (eg. show): ");

	while(my ($level,$label) = each %accessLevels)
	{
		my $newObj = Common::DB::Item::Permission->Lookup(application => $app,
													   area => $area,
													   command => $command,
													   access_level_id => $level);
		if($newObj && $newObj->access_level_id)
		{
			output("$label already has access to: $app - $area - $command");
		}
		else
		{
			$newObj = Common::DB::Item::Permission->Create();
			$newObj->application($app);
			$newObj->area($area);
			$newObj->command($command);
			$newObj->access_level_id($level);
			$newObj->enabled(1);

			$newObj->save();
			output("Success! Command created and $label granted access to: $app - $area - $command");
		}
	}

	my $another = getInput("\nCreate another? (y/N) ");
	if($another =~ /y(es)?/i)
	{
		goto COMMAND;
	}
	else
	{
		output("Thank you.");
	}

	return 1;
}

sub getInput
{
	my $prompt = shift;
	print $prompt;
	my $input = <STDIN>;
	chomp($input);
	return $input;
}

sub usage
{
	my $err = shift;
		
	print "ERROR: $err\n";
		
	return 1;
}

