%# BEGIN BPS TAGGED BLOCK {{{
%#
%# COPYRIGHT:
%#
%# This software is Copyright (c) 1996-2013 Best Practical Solutions, LLC
%#                                          <sales@bestpractical.com>
%#
%# (Except where explicitly superseded by other copyright notices)
%#
%#
%# LICENSE:
%#
%# This work is made available to you under the terms of Version 2 of
%# the GNU General Public License. A copy of that license should have
%# been provided with this software, but in any event can be snarfed
%# from www.gnu.org.
%#
%# This work 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., 51 Franklin Street, Fifth Floor, Boston, MA
%# 02110-1301 or visit their web page on the internet at
%# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
%#
%#
%# CONTRIBUTION SUBMISSION POLICY:
%#
%# (The following paragraph is not intended to limit the rights granted
%# to you to modify and distribute this software under the terms of
%# the GNU General Public License and is only of importance to you if
%# you choose to contribute your changes and enhancements to the
%# community by submitting them to Best Practical Solutions, LLC.)
%#
%# By intentionally submitting any modifications, corrections or
%# derivatives to this work, or any other work intended for use with
%# Request Tracker, to Best Practical Solutions, LLC, you confirm that
%# you are the copyright holder for those contributions and you grant
%# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
%# royalty-free, perpetual, license to use, copy, create derivative
%# works based on those contributions, and sublicense and distribute
%# those contributions and any derivatives thereof.
%#
%# END BPS TAGGED BLOCK }}}
<& /Elements/Header, Title => $title &>
<& /Elements/Tabs &>

<& /Elements/ListActions, actions => \@results &>

<form action="<% RT->Config->Get('WebPath') %>/AssetTracker/Asset/Create.html" method="post" enctype="multipart/form-data" name="AssetCreate">
  <input type="hidden" class="hidden" name="id" value="new" />

% $m->callback( CallbackName => 'FormStart', TypeObj => $TypeObj, ARGSRef => \%ARGS );

<div id="Asset-Create-basics">
<a name="basics"></a>	

<div id="asset-create-metadata">
    <&| /Widgets/TitleBox, title => $title, class=>'asset-info-basics' &>
    <input type="hidden" class="hidden" name="Type" value="<% $TypeObj->Id %>" />
    <table width="100%" border="0">
    <& /AssetTracker/Asset/Elements/EditBasics,
        InTable => 1,
        fields  => [
            {
                name => 'Name',
                html => '<input name="Name" value="'.$m->interp->apply_escapes( $ARGS{'Name'} || '', 'h' ).'" />',
            },
            {   name => 'Type',
                comp => '/AssetTracker/Asset/Elements/ShowType',
                args => {
                    TypeObj => $TypeObj,
                },
            },
            {   name => 'Status',
                comp => '/AssetTracker/Elements/SelectStatus',
                args => {
                    Name            => "Status",
                    Default         => $ARGS{Status} || $TypeObj->Lifecycle->DefaultOnCreate,
                    DefaultValue    => 0,
                    SkipDeleted     => 1,
                    TypeObj         => $TypeObj,
                },
            },
            {
                name => 'Description',
                html => '<input name="Description" value="'.$m->interp->apply_escapes( $ARGS{'Description'} || '', 'h' ).'" />',
            },
        ]
        &>

%foreach my $role ( $TypeObj->RoleGroupTypes() ) {
<tr>
<td class="label">
<% $role %>:
</td>
<td class="value" colspan="5"><& /Elements/EmailInput, Name => $role, Size => undef, Default => $ARGS{$role} &></td>
</tr>
%}

% $m->callback( CallbackName => 'AfterRoles', ARGSRef => \%ARGS );

      <& /AssetTracker/Asset/Elements/EditCustomFields, %ARGS, TypeObj => $TypeObj, InTable => 1 &>
%#      <& /AssetTracker/Asset/Elements/EditTransactionCustomFields, %ARGS, TypeObj => $TypeObj, InTable => 1 &>
    </table>
  </&>
% $m->callback( CallbackName => 'AfterBasics', TypeObj => $TypeObj, ARGSRef => \%ARGS );
</div>

<div id="asset-info-links">
<&| /Widgets/TitleBox, title => loc('Links'), class=> 'asset-info-links' &>

<em><&|/l&>(Enter ticket ids or URLs, separated with spaces)</&></em>
<table border="0">
%foreach my $type ( @link_order ) {
<tr><td class="label"><&|/l&><% $link_types{$type}{Name} %></&></td>
% if ( $link_types{$type}{Mode} eq 'Target' ) {
    <td><input size="10" name="new-<% $link_types{$type}{Type} %>" value="<% $ARGS{"new-$link_types{$type}{Type}"} || '' %>" /></td>
% } elsif ( $link_types{$type}{Mode} eq 'Base' ) {
    <td><input size="10" name="<% $link_types{$type}{Type} %>-new" value="<% $ARGS{"$link_types{$type}{Type}-new"} || '' %>" /></td>
% }
</tr>
%}

</table>
</&>
</div>
<br />

<& /Elements/Submit, Label => loc("Create"), id => 'SubmitAsset' &>
</div>
</form>

<%INIT>
$m->callback( CallbackName => "Init", ARGSRef => \%ARGS );
my $Type = $ARGS{Type};
$session{DefaultType} = $Type;

my %link_types = %{ RTx::AssetTracker::Asset::LINKTYPEMAP() };
my @link_order =    RTx::AssetTracker::Asset::LINKORDER();

if ($CloneAsset) {
    my $CloneAssetObj = RTx::AssetTracker::Asset->new( $session{CurrentUser} );
    $CloneAssetObj->Load($CloneAsset)
        or Abort( loc("Asset could not be loaded") );

    my $clone = { };

    foreach my $role ( $CloneAssetObj->TypeObj->RoleGroupTypes() ) {
	my $role_method = $role . 'RoleGroup';
        $clone->{$role} = join( ',', $CloneAssetObj->$role_method->MemberEmailAddressesAsString );
    }

    $clone->{$_} = $CloneAssetObj->$_()
	for qw/Name Description Status/;

    if (0) {    # Temporarily disabled
        my $members = $CloneAssetObj->Members;
        my ( @members, @members_of, @refers, @refers_by, @depends, @depends_by );
        my $refers = $CloneAssetObj->RefersTo;
        while ( my $refer = $refers->Next ) {
            push @refers, $refer->LocalTarget;
        }
        $clone->{'new-RefersTo'} = join ' ', @refers;

        my $refers_by = $CloneAssetObj->ReferredToBy;
        while ( my $refer_by = $refers_by->Next ) {
            push @refers_by, $refer_by->LocalBase;
        }
        $clone->{'RefersTo-new'} = join ' ', @refers_by;
        my $depends = $CloneAssetObj->DependsOn;
        while ( my $depend = $depends->Next ) {
            push @depends, $depend->LocalTarget;
        }
        $clone->{'new-DependsOn'} = join ' ', @depends;

        my $depends_by = $CloneAssetObj->DependedOnBy;
        while ( my $depend_by = $depends_by->Next ) {
            push @depends_by, $depend_by->LocalBase;
        }
        $clone->{'DependsOn-new'} = join ' ', @depends_by;

        while ( my $member = $members->Next ) {
            push @members, $member->LocalBase;
        }
        $clone->{'MemberOf-new'} = join ' ', @members;

        my $members_of = $CloneAssetObj->MemberOf;
        while ( my $member_of = $members_of->Next ) {
            push @members_of, $member_of->LocalTarget;
        }
        $clone->{'new-MemberOf'} = join ' ', @members_of;

    }

    my $cfs = $CloneAssetObj->TypeObj->AssetCustomFields();
    while ( my $cf = $cfs->Next ) {
        my $cf_id     = $cf->id;
        my $cf_values = $CloneAssetObj->CustomFieldValues( $cf->id );
        my @cf_values;
        while ( my $cf_value = $cf_values->Next ) {
            push @cf_values, $cf_value->Content;
        }
        $clone->{"Object-RTx::AssetTracker::Asset--CustomField-$cf_id-Value"} = join "\n",
            @cf_values;
    }

    $clone->{'ChangeComment'} = "Cloned from asset #$CloneAsset.";

    for ( keys %$clone ) {
        $ARGS{$_} = $clone->{$_} if not defined $ARGS{$_};
    }
}

my @results;

my $title = loc("Create a new asset");

my $TypeObj = RTx::AssetTracker::Type->new($session{'CurrentUser'});
$TypeObj->Load($Type) || Abort(loc("Type could not be loaded."));

$m->callback( TypeObj => $TypeObj, title => \$title, results => \@results, ARGSRef => \%ARGS );

$TypeObj->Disabled && Abort(loc("Cannot create assets of a disabled type."));

my $CFs = $TypeObj->AssetCustomFields();

my $ValidCFs = $m->comp(
    '/Elements/ValidateCustomFields',
    CustomFields => $CFs,
    ARGSRef => \%ARGS,
    NamePrefix => "Object-RTx::AssetTracker::Asset--CustomField-"
);

my $skip_create = 0;
$m->callback( CallbackName => 'BeforeCreate', ARGSRef => \%ARGS, skip_create => \$skip_create, 
              results => \@results );

if (defined($ARGS{'id'}) and $ARGS{'id'} eq 'new') { # new asset?
    if ( $ValidCFs && !$skip_create) {
        $m->comp('Display.html', %ARGS);
        $RT::Logger->crit("After display call; error is $@");
        $m->abort();
    }
    elsif ( !$ValidCFs ) {
        # Invalid CFs
        while (my $CF = $CFs->Next) {
            my $msg = $m->notes('InvalidField-' . $CF->Id) or next;
            push @results, $CF->Name . ': ' . $msg;
        }
    }
}
</%INIT>

<%ARGS>
$CloneAsset => undef
</%ARGS>
