& Elements/Header, Title => loc('Apikeys') &>
<& /Elements/ListActions, actions => \@results &>
<& Elements/ApikeyGeneration, 
    groups  => \%group_map,
    %ARGS 
&>
% if(@recs){
CIF API keys
<& Elements/ApikeyDisplay, 
    recs    => \@recs,
    groups  => \%group_map,
    %ARGS 
&>
% }
<& Elements/ApikeyDisplayGroups,
    groups  => \%group_map,
    %ARGS
&>
<%INIT>
require CIF::WebAPI::APIKey;
my $user = $session{'CurrentUser'}->UserObj();
my $g = $user->OwnGroups();
my %group_map;
while(my $grp = $g->Next()){
    next unless($grp->Name() =~ /^DutyTeam (\S+)/);
    my $guid = lc($1);
    my $priority = $grp->FirstCustomFieldValue('CIFGroupPriority');
    $group_map{$guid} = $priority;
}
$group_map{'everyone'} = 1000;
my @sorted = sort { $group_map{$a} <=> $group_map{$b} } keys(%group_map);
if($GenerateKey){
    my $found = 0;
    if(ref($add_groups) eq 'ARRAY'){
        foreach(@$add_groups){
            $found = 1 if($_ eq $default_group);
        }
    } else {
        $found = 1 if($add_groups eq $default_group);
    }
    unless($found){
        push(@results,'default group must be in your Groups selection');
    } else {
        require RT::CIFMinimal;
        my $id = RT::CIFMinimal::generate_apikey({
            user            => $user,
            description     => $key_description,
            default_guid    => $default_group,
            groups          => $add_groups,
        });
        if($id){
            push(@results,'key '.$id->uuid().' successfully generated');
        } else {
            push(@results,'key generation failed');
        }
    }
}
if($PurgeKey){
    my $r = CIF::WebAPI::APIKey->retrieve(uuid => $uuid);
    my $_uuid = $r->uuid();
    if($r->delete()){
        push(@results,$_uuid.' deleted');
    } else {
        push(@results,'error trying to delete: '.$_uuid);
    }
}
my @recs = CIF::WebAPI::APIKey->search(uuid_alias => $user->EmailAddress());
use Data::Dumper;
#A hack to make sure that session gets rewritten.
$session{'i'}++;
%INIT>
<%ARGS>
$GenerateKey => undef
$PurgeKey => undef
$uuid => undef
$key_description => undef
@results => undef
$default_group => undef
$add_groups => undef
%ARGS>