<%INIT>
my $request_path = $HTML::Mason::Commands::r->path_info;

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

#warn keys %session;

my $assets;
eval {
    $assets = Menu->child(  assets => title => loc('Assets'), path => '/AssetTracker/index.html', sort_order => 3 );
};
if ($@) {
    return;
}

$assets->child( new => title => loc('New Search') => path => "/AssetTracker/Search/Build.html?NewQuery=1" );

    if ( $request_path =~ m{^/AssetTracker/Asset/} ) {
        if ( ( $m->request_args->{'id'} || '' ) =~ /^(\d+)$/ ) {
            my $id  = $1;
            my $obj = RTx::AssetTracker::Asset->new( $session{'CurrentUser'} );
            $obj->Load($id);

            my $tabs = PageMenu();

            $tabs->child( display => title => loc('Display') => path => "/AssetTracker/Asset/Display.html?id=" . $id );

            $tabs->child( history => title => loc('History') => path => "/AssetTracker/Asset/History.html?id=" . $id );

            my %can = %{ $obj->CurrentUser->PrincipalObj->HasRights( Object => $obj ) };
            $can{'_ModifyOwner'} = $can{'OwnAsset'} || $can{'TakeAsset'} || $can{'StealAsset'};
            my $can = sub {
                unless ($_[0] eq 'ExecuteCode') {
                    return $can{$_[0]} || $can{'SuperUser'};
                } else {
                    return !RT->Config->Get('DisallowExecuteCode')
                        && ( $can{'ExecuteCode'} || $can{'SuperUser'} );
                }
            };

            # comment out until we can do it for an individual custom field
            #if ( $can->('ModifyAsset') || $can->('ModifyCustomField') ) {
            $tabs->child( basics => title => loc('Basics'), path => "/AssetTracker/Asset/Modify.html?id=" . $id, );

            #}

            if ( $can->('ModifyAsset') || $can->('_ModifyOwner') || $can->('Watch') || $can->('WatchAsAdminCc') ) {
                $tabs->child( people => title => loc('People'), path => "/AssetTracker/Asset/ModifyPeople.html?id=" . $id,);
            }

            if ( $can->('ModifyAsset') && RT->Config->Get('EnableIP') ) {
                $tabs->child( ips => title => loc('IPs'), path => "/AssetTracker/Asset/ModifyIPs.html?id=" . $id, );
            }
            if ( $can->('ModifyAsset') ) {
                $tabs->child( fields => title => loc('Fields'), path => "/AssetTracker/Asset/ModifyFields.html?id=" . $id, );
                $tabs->child( links => title => loc('Links'), path => "/AssetTracker/Asset/ModifyLinks.html?id=" . $id, );
            }
            #if ( $can->('ModifyAsset') || $can->('ModifyCustomField') || $can->('_ModifyOwner') ) {
            $tabs->child( jumbo => title => loc('Jumbo'), path => "/AssetTracker/Asset/ModifyAll.html?id=" . $id, );
            #}

            #AT removed lifecycle stuff

            #AT removed ticket taking/stealing

            if ( defined $session{"assets"} ) {
                # we have to update session data if we get new ItemMap
                my $updatesession = 1 unless ( $session{"assets"}->{'item_map'} );

                my $item_map = $session{"assets"}->ItemMap;

                if ($updatesession) {
                    $session{"assets"}->PrepForSerialization();
                }

                my $search = $assets; #Menu()->child('search');
                # Don't display prev links if we're on the first ticket
                if ( $item_map->{$id}->{prev} ) {
                    $search->child( 'first', title => ' ' . loc('First'), escape_title => 0, class => "nav",
                                    path => "/AssetTracker/Asset/Display.html?id=" . $item_map->{first});
                    $search->child( prev => title => '< ' . loc('Prev') => class => "nav",
                                    path => "/AssetTracker/Asset/Display.html?id=" . $item_map->{$id}->{prev});
                }
                # Don't display next links if we're on the last ticket
                if ( $item_map->{$id}->{next} ) {
                    $search->child( next       => title => loc('Next') . ' >' => class => "nav",
                                    path => "/AssetTracker/Asset/Display.html?id=" . $item_map->{$id}->{next});
                    $search->child( last        => title => loc('Last') . ' >>' => class => "nav",
                                    path => "/AssetTracker/Asset/Display.html?id=" . $item_map->{last});
                }
            }
        }
    }

    if ( $request_path =~ m{^/AssetTracker/(?:Asset|Search)/}
        || ( $request_path =~ m{^/AssetTracker/index\.html} && $DECODED_ARGS->{'q'} ) ) {
        my $search = $assets; #->child('search');
        my $args      = '';
        my $has_query = '';
        my $current_search = $session{"CurrentAssetSearchHash"} || {};
        my $search_id = $m->request_args->{'SavedSearchLoad'} || $m->request_args->{'SavedSearchId'} || $search->{'SearchId'} || '';

        $has_query = 1 if ( $m->request_args->{'Query'} or $current_search->{'Query'} );

        my %query_args = (
            SavedSearchId => ( $search_id eq 'new' ) ? undef : $search_id,
            SavedChartSearchId => $m->request_args->{'SavedChartSearchId'} || $current_search->{SavedChartSearchId},
            Query => $m->request_args->{'Query'} || $current_search->{'Query'},
            Format => $m->request_args->{'Format'} || $current_search->{'Format'},
            OrderBy => $m->request_args->{'OrderBy'} || $current_search->{'OrderBy'} ||'',
            Order => $m->request_args->{'Order'} || $current_search->{'Order'} ||'',
            Page => $m->request_args->{'Page'} || $current_search->{'Page'},
            RowsPerPage => ( defined $m->request_args->{'RowsPerPage'}
                             ? $m->request_args->{'RowsPerPage'}
                             : $current_search->{'RowsPerPage'})
                         );
        for my $field (qw(Order OrderBy)) {
            if ( ref( $query_args{$field} ) eq 'ARRAY' ) {
                $query_args{$field} = join( "|", @{ $query_args{$field} } );
            } elsif (not defined $query_args{$field}) {
                delete $query_args{$field};
            }
        }

        $args = "?" . ($QueryString || $query_string->(%query_args));


        my $current_search_menu;
        if ( $request_path =~ m{^/AssetTracker/Asset} ) {
            $current_search_menu = $search->child( current_search => title => loc('Current Search') );
            $current_search_menu->path("/AssetTracker/Search/Results.html$args") if $has_query;
        } else {
            $current_search_menu = PageMenu();
        }

        $current_search_menu->child( edit_search => title => loc('Edit Search') =>
                                     path => "/AssetTracker/Search/Build.html" . ( ($has_query) ? $args : '' ) );
        $current_search_menu->child( loc('Advanced') => path => "/AssetTracker/Search/Edit.html$args" );
        if ($has_query) {
            $current_search_menu->child( results => title => loc('Show Results') => path => "/AssetTracker/Search/Results.html$args" );
        }

        if ( $has_query ) {
            my $bulk = $current_search_menu->child( bulk => title => loc('Bulk Update'));
            $bulk->child( batch => title => loc('Batch Update multiple assets'), path => "/AssetTracker/Search/Bulk.html$args" );
            $bulk->child( grid  => title => loc('Grid Update multiple assets'),  path => "/AssetTracker/Search/Grid.html$args" );

            my $more = $current_search_menu->child( more => title => loc('Feeds') );

            $more->child( spreadsheet => title => loc('Spreadsheet'), path => "/AssetTracker/Search/Results.tsv$args" );
            $more->child( importable => title => loc('Importable Spreadsheet'), path => "/AssetTracker/Search/Export.html$args" );

            if ($request_path =~ m{^/AssetTracker/Search/Results.html}
                &&                        #XXX TODO better abstraction
                $session{'CurrentUser'}->HasRight( Right => 'SuperUser', Object => RT->System )) {
                my $shred_args = $query_string->(
                    search          => 1,
                    plugin          => 'Assets',
                    'Assets:query' => $query_args{'Query'},
                    'Assets:limit' => $query_args{'Rows'},
                );

                $more->child( 'shredder' => title => loc('Shredder'),
                                path => '/Admin/Tools/Shredder/?' . $shred_args);
            }
        }
    }

    if ( $request_path =~ m{^/AssetTracker/Admin/Types} ) {
        my $type = 'Types';
        my $tabs = PageMenu();

        my $section;
        if ( $request_path =~ m{^/AssetTracker/Admin/$type/?(?:index.html)?$}
             || (    $request_path =~ m{^/AssetTracker/Admin/$type/(?:Modify.html)$}
                  && $m->request_args->{'Create'} )
           )

        {
            $section = $tabs;

        } else {
            $section = $tabs->child( select => title => loc('Asset Types'),
                                     path => "/AssetTracker/Admin/$type/" );
        }

        $section->child( select => title => loc('Select'),
                         path   => "/AssetTracker/Admin/$type/" );
        $section->child( create => title => loc('Create'),
                         path => "/AssetTracker/Admin/$type/Modify.html?Create=1" );
    }

    if ( $request_path =~ m{^/AssetTracker/Admin/Types} ) {
        if ( $m->request_args->{'id'} && $m->request_args->{'id'} =~ /^\d+$/
                ||
              $m->request_args->{'Type'} && $m->request_args->{'Type'} =~ /^\d+$/
                ) {
            my $id = $m->request_args->{'Type'} || $m->request_args->{'id'};
            my $type_obj = RTx::AssetTracker::Type->new( $session{'CurrentUser'} );
            $type_obj->Load($id);

            my $type = PageMenu();
            $type->child( basics => title => loc('Basics'), path => "/AssetTracker/Admin/Types/Modify.html?id=" . $id );
            $type->child( people => title => loc('Watchers'), path => "/AssetTracker/Admin/Types/People.html?id=" . $id );
            my $templates = $type->child(templates => title => loc('Templates'),
                              path => "/AssetTracker/Admin/Types/Templates.html?id=" . $id);

            $templates->child(select => title => loc('Select'), path => "/AssetTracker/Admin/Types/Templates.html?id=".$id);
            $templates->child( create => title => loc('Create'), path => "/AssetTracker/Admin/Types/Template.html?Create=1;AssetType=".$id);

            my $scrips = $type->child( scrips => title => loc('Scrips'), path => "/AssetTracker/Admin/Types/Scrips.html?id=" . $id);

            $scrips->child( select => title => loc('Select'), path => "/AssetTracker/Admin/Types/Scrips.html?id=" . $id );
            $scrips->child( create => title => loc('Create'), path => "/AssetTracker/Admin/Types/Scrip.html?Create=1;AssetType=" . $id);

            my $ticket_cfs = $type->child( 'ticket-custom-fields' => title => loc('Asset Custom Fields'),
                  path => '/AssetTracker/Admin/Types/CustomFields.html?SubType=RTx::AssetTracker::Asset&id=' . $id );

            $type->child( 'group-rights' => title => loc('Group Rights'), path => "/AssetTracker/Admin/Types/GroupRights.html?id=".$id );
            $type->child( 'user-rights' => title => loc('User Rights'), path => "/AssetTracker/Admin/Types/UserRights.html?id=" . $id );

        }
    }

    my $tools = Menu->child("tools");

    $tools->child( asset_import =>
        title       => loc('Asset Import'),
        description => loc('Import assets from an Excel 94 XML formatted file'),
        path        => '/AssetTracker/Tools/Import.html',
    );

    my $admin = $tools->child("config");
    if ($admin) {
        my $types = $admin->child( 'asset-types' => title => loc('Asset Types'), path => '/AssetTracker/Admin/Types/', description => loc('Manage asset types and asset-specific properties') );
        $types->child( select => title => loc('Select'), path => "/AssetTracker/Admin/Types/index.html" );
        $types->child( create => title => loc('Create'), path => "/AssetTracker/Admin/Types/Modify.html?Create=1" );

        my $cfadmin = $admin->child("global")->child("custom-fields");
        $cfadmin->child( assets => title => loc('Assets') => text => loc('Select custom fields for all assets'),
                            path => '/AssetTracker/Admin/Global/CustomFields/Type-Assets.html');
        $cfadmin->child( types => title => loc('Asset Types') => text => loc('Select custom fields for asset types'),
                            path => '/AssetTracker/Admin/Global/CustomFields/Types.html');

    }

    PageWidgets()->child( create_asset => raw_html => $m->scomp('/AssetTracker/Elements/CreateAsset'), sort_order => 99 );
    PageWidgets()->child( AT_simple_search => raw_html => $m->scomp('/AssetTracker/Elements/SimpleSearch'), sort_order => 98 );

</%INIT>
<%ARGS>
$show_menu => 1
$QueryString => ''
</%ARGS>
