%# BEGIN LICENSE BLOCK
%# 
%#  Copyright (c) 2002-2003 Jesse Vincent <jesse@bestpractical.com>
%#  
%#  This program is free software; you can redistribute it and/or modify
%#  it under the terms of version 2 of the GNU General Public License 
%#  as published by the Free Software Foundation.
%# 
%#  A copy of that license should have arrived with this
%#  software, but in any event can be snarfed from www.gnu.org.
%# 
%#  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.
%# 
%# END LICENSE BLOCK
<%INIT>

my $query_string = sub {
    my %args = @_;
    my $u    = URI->new();
    $u->query_form(%args);
    return $u->query || '';
};

my $root = Menu->child( rtir => title => loc('RTIR'), path => '/RTIR/' );

my $search = $root->child( search => title => loc('Search'), path => '/RTIR/Search/' );
$search->child( new => title => loc('New Query'), path => '/RTIR/Search/?NewQuery=1' );
# XXX: query string
$search->child( build => title => loc('Build Search'), path => '/RTIR/Search/' );
if ( $session{'CurrentSearchHash'} ) {
    $search->child( results => title => loc('Show Results'), path => '/RTIR/Search/Results.html' );
} else {

}

$root->child(
    incidents => title => loc('Incidents'),
    path => '/RTIR/Search/Results.html?Queue=Incidents'
)->child(
    create => title => loc('Create'),
    path => '/RTIR/Create.html?Queue=Incidents',
);
$root->child(
    reports => title => loc('Incident Reports'),
    path => '/RTIR/Search/Results.html?Queue=Incident%20Reports'
)->child(
    create => title => loc('Create'),
    path => '/RTIR/Create.html?Queue=Incident%20Reports',
);
$root->child(
    investigations => title => loc('Investigations'),
    path => '/RTIR/Search/Results.html?Queue=Investigations'
)->child(
    create => title => loc('Create'),
    path => '/RTIR/Create.html?Queue=Investigations',
);
unless ( RT->Config->Get('RTIR_DisableBlocksQueue') ) {
    $root->child(
        blocks => title => loc('Blocks'),
        path => '/RTIR/Search/Results.html?Queue=Blocks'
    )->child(
        create => title => loc('Create'),
        path => '/RTIR/Create.html?Queue=Blocks',
    );
}

my $tools = $root->child( tools => title => loc('Tools'), path => '/RTIR/Tools/' );
$tools->child( lookup => title => loc('Lookup'), path => '/RTIR/Tools/Lookup.html' );
$tools->child( reporting => title => loc('Reporting'), path => '/RTIR/Reporting/' );
my $scripted_actions = $tools->child( scripted_actions => title => loc('Scripted Action') );
$scripted_actions->child( email => title => loc('By Email address'), path => '/RTIR/Tools/ScriptedAction.html' );
$scripted_actions->child( ip => title => loc('By IP address'), path => '/RTIR/Tools/ScriptedAction.html?loop=IP' );

my $request_path = $HTML::Mason::Commands::r->path_info;
return unless $request_path =~ m{^/RTIR/};

my $args = $m->request_args;
my $re_rtir_types = '(?:'. join( '|', map "\Q$_\E", RT::IR->Types ) .')';

my $search_arguments = sub {
    my %res = ();
    my @query_fields = qw(Query Format RowsPerPage Page OrderBy Order);
    if ( my $refined = $m->notes('RefinedSearch') ) {
        @res{ @query_fields } = @{ $refined->{'query'} }{ @query_fields };
    } else {
        @res{ @query_fields } = @{ $args }{ @query_fields };
    }
    delete $res{$_} foreach grep !defined $res{$_}, keys %res;
    return %res;
};

if ( $request_path =~ m{^/RTIR/(?:$re_rtir_types/)?(Display|Edit|Update)\.html$} ) {
    my $id = $args->{'id'};

    # we'll never get here unless ticket is there and it's rtir's type
    my $ticket = RT::Ticket->new( $session{'CurrentUser'} );
    $ticket->Load($id);
    $id = $ticket->id;

    my $queue = $ticket->QueueObj;
    my $type = RT::IR::TicketType( Queue => $queue );

    my %can;
    my $can = sub {
        return $can{$_[0]} if exists $can{$_[0]};
        return $can{$_[0]} = $ticket->CurrentUserHasRight( $_[0] );
    };

    my $actions_tab = PageMenu()->child( actions => title => loc('Actions'), sort_order  => 95 );

    PageMenu()->child( display => title => loc('Display'), path => "/RTIR/Display.html?id=$id" );

    # RT4 TODO: something wrong, this doesn't work
    if ( $session{'tickets'} ) {
        # we have to update session data if we get new ItemMap
        my $updatesession = 1 unless ( $session{"tickets"}->{'item_map'} );
        my $item_map = $session{"tickets"}->ItemMap;
        $session{"tickets"}->PrepForSerialization
            if $updatesession;

        # Don't display prev links if we're on the first ticket
        my $top = PageMenu();
        if ( my $t = $item_map->{$id}->{'prev'} ) {
            $top = $top->child(
                previouse => path => "/RTIR/Display.html?id=$id",
                title => '< ' . loc('Prev')
            );
        }
        if ( my $t = $item_map->{'first'} ) {
            $top->child(
                first => path  => "/RTIR/Display.html?id=$t",
                title => '<< ' . loc('First')
            ) if $t != $id;
        }

        $top = PageMenu();
        if ( my $t = $item_map->{$id}->{'next'} ) {
            $top = $top->child(
                next => path  => "/RTIR/Display.html?id=$t",
                title => loc('Next') . ' >'
            );
        }
        if ( my $t = $item_map->{'last'} ) {
            $top->child(
                last => path  => "/RTIR/Display.html?id=$t",
                title => loc('Last') . ' >>'
            ) if $t != $id;
        }
    }

    if ( $can->('ModifyTicket') ) {
        PageMenu()->child( edit => title => loc('Edit'), path => "/RTIR/Edit.html?id=$id" );
        PageMenu()->child( split => title => loc('Split'), path => "/RTIR/Split.html?Split=$id" );
        # XXX: we're missing query string here
        PageMenu()->child( merge => title => loc('Merge'), path => "/RTIR/Merge/?id=$id" );
        PageMenu()->child( advanced => title => loc('Advanced'), path => "/RTIR/Advanced.html?id=$id" );
    }

    if ( $can->('OwnTicket') ) {
        if ( $ticket->Owner == $RT::Nobody->id ) {
            $actions_tab->child(
                take => title => loc('Take'),
                path  => "/RTIR/Display.html?Action=Take&id=$id",
            ) if $can->('ModifyTicket') || $can->('TakeTicket');
        } elsif ( $ticket->Owner != $session{CurrentUser}->id ) {
            $actions_tab->child(
                steal => title => loc('Steal'),
                path  => "/RTIR/Display.html?Action=Steal&id=$id",
            ) if $can->('ModifyTicket') || $can->('StealTicket');
        }
    }

    if ( $can->('ModifyTicket') || $can->('ReplyToTicket') ) {
        if ( $type eq 'Incident' ) {
            $actions_tab->child(
                reply_reporters => title => loc('Reply to Reporters'),
                path  => "/RTIR/Incident/Reply/?id=$id&SelectAllTickets=1",
            );
            $actions_tab->child(
                reply_all => title => loc('Reply to All'),
                path  => "/RTIR/Incident/Reply/?id=$id&SelectAllTickets=1&All=1",
            );
        } else {
            $actions_tab->child(
                reply => title => loc('Reply'),
                path  => "/RTIR/Update.html?id=$id&Action=Respond",
            );
        }
    }

    my $i = 0;
    my $status = $ticket->Status;
    my $lifecycle = $queue->Lifecycle;
    foreach my $info ( $lifecycle->Actions( $status ) ) {
        my $next = $info->{'to'};
        next unless $lifecycle->IsTransition( $status => $next );

        my %args = (%$info, id => $id);
        delete @args{qw(to from label update)};

        # if user will be owner then he will get more rights
        # TODO: check actually if he will get required rights
        if ( !$args{'TakeOrStealFirst'} || $session{'CurrentUser'}->id == $ticket->Owner ) {
            my $check = $lifecycle->CheckRight( $status => $next );
            next unless $can->( $check );
        }

        my $path = '/RTIR/';
        $path .= 'Incident/' if $type eq 'Incident';
        if ( my $update = $info->{'update'} ) {
            $path .= $type eq 'Incident'? 'Reply/' : 'Update.html';
            $path .= "?". $m->comp(
                '/Elements/QueryString',
                %args,
                Action => $update,
                Status => $next,
            );
        } else {
            $path .= "Display.html?". $m->comp(
                '/Elements/QueryString',
                %args,
                Status => $next,
            );
        }
        $actions_tab->child(
            lc($info->{'label'} || $next),
            title => loc( $info->{'label'} || ucfirst($next) ),
            path  => $path,
        );
    }

    if ( $can->('ModifyTicket') || $can->('CommentOnTicket') ) {
        $actions_tab->child(
            comment => title => loc('Comment'),
            path  => "/RTIR/Update.html?Action=Comment&id=$id",
        );
    }

    PageMenu()->child(
        bookmark => raw_html => $m->scomp( '/Ticket/Elements/Bookmark', id => $id ),
        sort_order   => 99
    );
} elsif ( $request_path =~ m{^/RTIR/Link/(ToIncident|FromIncident)/} ) {
    my $direction = $1;
    my $queue = $args->{'Queue'};
    my $type = RT::IR::TicketType( Queue => $queue || 'Incidents' );

    my $ticket = RT::Ticket->new( $session{'CurrentUser'} );
    $ticket->Load( $args->{'id'} );
    my $id = $ticket->id;

    my %args = (
        $search_arguments->(),
        id => $id,
        Queue => $queue,
    );

    PageMenu()->child(
        link => title => loc('Show Results'),
        path => "/RTIR/Link/$direction/?". $query_string->( %args ),
    );
    PageMenu()->child(
        edit_search => title => loc('Edit Search'),
        path => "/RTIR/Link/$direction/Refine.html?". $query_string->( %args ),
    );
    PageMenu()->child(
        new_search => title => loc('New Search'),
        path => "/RTIR/Link/$direction/Refine.html?". $query_string->(
            NewQuery => 1, id => $id, Queue => $queue,
        ),
    );
    PageMenu()->child(
        new => title => loc("New $type"),
        path => !$queue
            ? "/RTIR/Create.html?Child=$id&Queue=Incidents"
            : "/RTIR/Create.html?". $query_string->( Incident => $id, Queue => $queue )
        ,
    );
    PageMenu()->child(
        back => title => loc('Back to ticket #[_1]', $id),
        path => "/RTIR/Display.html?id=$id",
    );
} elsif ( $request_path =~ m{^/RTIR/Incident/Children/} ) {
    my $queue = $args->{'Queue'} || 'Incident Reports';
    my $type = RT::IR::TicketType( Queue => $queue );

    my $ticket = RT::Ticket->new( $session{'CurrentUser'} );
    $ticket->Load( $args->{'id'} );
    my $id = $ticket->id;

    my %args = (
        $search_arguments->(),
        id => $id,
        Queue => $queue,
    );

    PageMenu()->child(
        link => title => loc('Show Results'),
        path => "/RTIR/Incident/Children/?". $query_string->( %args ),
    );
    PageMenu()->child(
        edit_search => title => loc('Edit Search'),
        path => "/RTIR/Incident/Children/Refine.html?". $query_string->( %args ),
    );
    PageMenu()->child(
        new_search => title => loc('New Search'),
        path => "/RTIR/Incident/Children/Refine.html?". $query_string->(
            NewQuery => 1, id => $id, Queue => $queue,
        ),
    );
    PageMenu()->child(
        new => title => loc("New $type"),
        path => "/RTIR/Create.html?". $query_string->( Incident => $id, Queue => $queue ),
    );
    PageMenu()->child(
        back => title => loc('Back to ticket #[_1]', $id),
        path => "/RTIR/Display.html?id=$id",
    );
} elsif ( $request_path =~ m{^/RTIR/Merge/} ) {
    my $ticket = RT::Ticket->new( $session{'CurrentUser'} );
    $ticket->Load( $args->{'id'} );
    my $id = $ticket->id;

    my %args = (
        $search_arguments->(),
        id => $id,
    );

    PageMenu()->child(
        link => title => loc('Merge'),
        path => "/RTIR/Merge/?". $query_string->( %args ),
    );
    PageMenu()->child(
        edit_search => title => loc('Edit Search'),
        path => "/RTIR/Merge/Refine.html?". $query_string->( %args ),
    );
    PageMenu()->child(
        new_search => title => loc('New Search'),
        path => "/RTIR/Merge/Refine.html?". $query_string->(
            NewQuery => 1, id => $id,
        ),
    );
    PageMenu()->child(
        back => title => loc('Back to ticket #[_1]', $id),
        path => "/RTIR/Display.html?id=$id",
    );
} elsif ( $request_path =~ m{^/RTIR/Incident/Reply/} ) {
    my $ticket = RT::Ticket->new( $session{'CurrentUser'} );
    $ticket->Load( $args->{'id'} );
    my $id = $ticket->id;

    my %args = (
        $search_arguments->(),
        id => $id,
        All => $args->{'All'},
        Status => $args->{'Status'},
        Action => $args->{'Action'},
    );

    PageMenu()->child(
        link => title => loc('Reply'),
        path => "/RTIR/Incident/Reply/?". $query_string->( %args ),
    );
    PageMenu()->child(
        edit_search => title => loc('Edit Search'),
        path => "/RTIR/Incident/Reply/Refine.html?". $query_string->( %args ),
    );
    PageMenu()->child(
        new_search => title => loc('New Search'),
        path => "/RTIR/Incident/Reply/Refine.html?". $query_string->(
            NewQuery => 1, id => $id,
        ),
    );
    PageMenu()->child(
        back => title => loc('Back to ticket #[_1]', $id),
        path => "/RTIR/Display.html?id=$id",
    );
} elsif ( $request_path =~ m{^/RTIR/(Search/|Incident/BulkAbandon\.html$|Report/BulkReject\.html$)} ) {
    my %args = $search_arguments->();

    my $queue = $args->{'Queue'} || '';
    unless ( $queue ) {
        if ( $request_path =~ /Incident/ ) {
            $queue = 'Incidents';
        }
        elsif ( $request_path =~ /Report/ ) {
            $queue = 'Incident Reports';
        }
    }
    unless ( $queue ) {
        my (undef, @queues) = RT::IR->OurQuery( $args{'Query'} );
        $queue = $queues[0] if @queues == 1;
    }
    my $type = RT::IR::TicketType( Queue => $queue ) || '';

    $args{'Queue'} = $queue if $queue;

    PageMenu()->child(
        link => title => loc('Show Results'),
        path => "/RTIR/Search/Results.html?". $query_string->( %args ),
    );
    PageMenu()->child(
        edit_search => title => loc('Edit Search'),
        path => "/RTIR/Search/Refine.html?". $query_string->( %args ),
    );
    PageMenu()->child(
        new_search => title => loc('New Search'),
        path => "/RTIR/Search/Refine.html?". $query_string->(
            NewQuery => 1,
            Queue => $queue,
        ),
    );

    if ( $type eq 'Incident' ) {
        PageMenu()->child(
            report => title => loc('Report'),
            path => "/RTIR/Reporting/",
        );

        PageMenu()->child(
            abandon => title => loc('Bulk Abandon'),
            path => "/RTIR/Incident/BulkAbandon.html?". $query_string->( %args ),
        );
    }
    elsif ( $type eq 'Report' ) {
        PageMenu()->child(
            reject => title => loc('Bulk Reject'),
            path => "/RTIR/Report/BulkReject.html?". $query_string->( %args ),
        );
    }
    PageMenu()->child(
        chart => title => loc('Chart'),
        path => "/RTIR/Search/Reporting.html?". $query_string->( %args ),
    );

    my $more = PageMenu->child( more => title => loc('Feeds') );
    $more->child(
        spreadsheet => title => loc('Spreadsheet'),
        path => "/Search/Results.tsv?". $query_string->( %args ),
    );

    # other paths need query defined
    $args{'Query'} = RT::IR->Query( Queue => $args{'Queue'} )
        if !$args{'Query'} && $args{'Queue'};

    if ( $args{'Query'} ) {
        my $RSSPath = join '/', map $m->interp->apply_escapes( $_, 'u' ),
            $session{'CurrentUser'}->UserObj->Name,
            $session{'CurrentUser'}->UserObj->GenerateAuthString(
                join '', map $args{$_}||'', qw(Query Order OrderBy)
            )
        ;
        $more->child(
            rss => title => loc('RSS'),
            path => "/NoAuth/rss/$RSSPath/?". $query_string->(
                Query => $args{Query}, Order => $args{Order}, OrderBy => $args{OrderBy}
            ),
        );

        my $ical_path = join '/', map $m->interp->apply_escapes($_, 'u'),
            $session{'CurrentUser'}->UserObj->Name,
            $session{'CurrentUser'}->UserObj->GenerateAuthString( $args{Query} ),
            $args{Query}
        ;
        $more->child( ical => title => loc('iCal') => path => '/NoAuth/iCal/'.$ical_path);
    }

    if ( $args{'Query'} && $session{'CurrentUser'}->HasRight(
        Right => 'SuperUser', Object => RT->System
    ) ) {
        my $shred_args = $query_string->(
            search          => 1,
            plugin          => 'Tickets',
            'Tickets:query' => $args{'Query'},
            'Tickets:limit' => $args{'RowsPerPage'},
        );
        $more->child(
            shredder => title => loc('Shredder'),
            path => '/Admin/Tools/Shredder/?' . $shred_args
        );
    }
} elsif ( $request_path =~ m{^/RTIR/(?:$re_rtir_types/)?Split\.html$} ) {
    my $id = $args->{'Split'};

    PageMenu()->child(
        back => title => loc('Back to ticket #[_1]', $id),
        path => "/RTIR/Display.html?id=$id",
    );
}

if ( $session{'CurrentUser'}->HasRight(Right => 'ModifySelf', Object => $RT::System) ) {
    if ( $request_path =~ m{^/RTIR/(?:index\.html|)$} ) {
        PageMenu()->child( edit => title => loc('Edit'), path => '/RTIR/Prefs/Home.html' )
    }
    Menu->child('preferences')->child('settings')->child(
        rtir_home_page => title => loc('RTIR at a glance'),
        path => '/RTIR/Prefs/Home.html',
    );
}

PageWidgets()->child('simple_search')->raw_html( $m->scomp(
    '/Elements/SimpleSearch',
    SendTo => '/RTIR/index.html'
) );

</%INIT>
