<%doc>
edit.html - present a form to either insert a new object or update an existing one.

  Arguments:

    table -- name of table to create/edit
    id    -- row in a specific table if editing
    cancel - cancels all existing state and returns to null state
    submit - column names from any/all tables

  Possible states:

    - null 
    new page to create any table

    - table is set
    present page to create that table

    - table and id are set
    present page to edit particular instance of that table

    - submit
    Table has been submitted to be added/updated; go to View page.

</%doc>


<%attr>
title   => 'Edit' 
section => 'Generic'
</%attr>

<%args>
$table       => undef
$id          => undef
$user        => $ui->get_current_user($r)
$submit      => undef
$cancel      => undef
$showheader  => 1
$select_id   => undef
$selected    => undef
$dowindow    => undef
$state_digest => undef
$view         => 'all'
</%args>

<%init>
my %args;
my $DEBUG = 0;
my %reserved = (submit       => '',
		commit       => '',
		table        => '',
		showheader   => '',
		user         => '',
		select_id    => '',
		selected     => '',
		onload       => '',
		dowindow     => '',
		request      => '',
		page         => '',
		state_digest => '',
		);

my $manager = $ui->get_permission_manager($r);

##################################################
# grab arguments to this script
foreach my $j ( keys %ARGS ) {
    ################################################
    # in case apache makes the value an array, set to last value
    if( ref( $ARGS{$j} ) eq "ARRAY" ) {
	    my @t = @{ $ARGS{$j} };
	    $ARGS{$j} = $t[$#t];
    }
    next if( $j !~ /\w+/ );

  ################################################
  # Ignore fields that don't belong to the table
    next if exists $reserved{$j};
    
    # /_srch/ elements are added for javascript only
    # we don't need them here
    next if ($j =~ /_srch/ );
    
    ################################################
    # "/^_/" is added to avoid using reserved words in javascript
    # chop it off
    my $k = $j;
    $k =~ s/^_//;
    $args{$k} = $ARGS{$j};
}


##################################################
if( $DEBUG ) {
    print "ARGS: ";
    printf "<pre>%s</pre>\n", Dumper( \%ARGS );
    print "args: ";
    printf "<pre>%s</pre>\n", Dumper( \%args );
}

##################################################
# Start the actual work
#
if ( $table ){
    my $page = $ui->table_view_page($table);

    # Special cases
    if ( $table =~ /Picture/ ){
	if ( $args{upload} ){
	    eval {
		use Apache2::Upload;
		my $bindata;
		my $upload      = $r->upload("upload");
		my $upload_fh   = $upload->fh;
		my $size        = $upload->slurp($bindata);
		$args{bindata}  = $bindata;
		$args{filename} = $args{filename} || $upload->filename;
		delete $args{upload};
		delete $args{filetype} unless $args{filetype};
	    };
	    if ( my $e = $@ ){
		$m->comp('error.mhtml', error=>$e);
	    }
	}
	delete $args{upload}; # It's a fake column
    }

    if ( $id ){
	my $obj = $table->retrieve($id);
	unless ( $manager && $manager->can($user, "edit", $obj) ){
	    $m->comp('/generic/error.mhtml', error=>"You don't have permission to edit this object");
	}
	
	if ( $submit eq "Update" ){
	    $ui->localize_newlines($table, \%args);
	    my $new_digest = $obj->get_digest();
	    eval {
		Netdot::Model->do_transaction( sub{
		    if ( $state_digest && ($state_digest ne $new_digest) ){
			$ui->throw_user('This object changed while you were editing!');
		    }
		    $ui->check_value_lengths($table, \%args);
		    $obj->update(\%args);
					       });
	    };
	    if ( my $e = $@ ){
		$m->comp('error.mhtml', error=>$e);
	    }
	    
	    $m->comp($page, table=>$table, id=>$id, dowindow=>$dowindow );
	    
        }else{
            $m->comp('.show_form', table=>$table, id=>$id, view=>$view,
		     showheader=>$showheader, select_id=>$select_id, selected=>$selected, dowindow=>$dowindow );
        }
    }else{
	if ( $submit eq "Insert" ){
	    $ui->localize_newlines($table, \%args);
	    my $new;
	    eval{
		Netdot::Model->do_transaction( sub{
		    $ui->check_value_lengths($table, \%args);
		    $new = $table->insert(\%args);
					       });
	    };
	    if ( my $e = $@ ){
		$m->comp('error.mhtml', error=>$e);
	    }
	    if ( $dowindow ){
		$m->comp('.show_inserted', table=>$table, id=>$new->id,
			 showheader=>$showheader, select_id=>$select_id, selected=>$selected, dowindow=>$dowindow );
	    }
            else{
		$m->comp($page, table=>$table, id=>$new->id, dowindow=>$dowindow );
	    }

	}
        else{
	    $m->comp('.show_form', table=>$table, 
		     showheader=>$showheader, select_id=>$select_id, selected=>$selected, dowindow=>$dowindow, args=>\%args);
	}
    }
    
}else{
    $m->comp('table.mhtml', width=>2, link=>"edit.html", title => "Please select an object to create:");
}


</%init>



% ########################################################
% # BEGIN HTML STUFF
% ########################################################


<%def .show_form>
<%perl>
    if ( $ARGS{table} eq 'UserRight' || $ARGS{table} eq 'GroupRight'){
	# need to re-retrieve $user for some reason,
	# probably because it is a separate component
	my $user = $ui->get_current_user($r);
	my $user_type = $user->getAttribute('USER_TYPE');
	if ( $user_type eq "Admin" ) {
	    $m->comp('access_right_form.html', %ARGS);
	} else {
	    $m->comp('/generic/error.mhtml', error=>"You don't have permission to manage users!");
	}
    }
    else{
    	$m->comp('.show_generic_form', %ARGS);
    }
</%perl>
</%def>

% ########################################################
% # HTML form wrapper for the form component
% ########################################################

<%def .show_generic_form>

<%args>
$table
$id         => undef
$select_id  => undef
$selected   => undef
$showheader => undef
$dowindow   => undef
%args       => undef
$view       => 'all'
</%args>

<%init>

if ( !defined($dowindow) ){
     $dowindow = 0;
}
my $title = "$table " . $ui->table_descr_link($table, "[?]");
</%init>


%if ( ! $showheader ){
%	$m->clear_buffer;
<html>
  <head>
      <link rel="stylesheet" href="<% $r->dir_config('NetdotPath') %>css/style.css" type="text/css">
  </head>      
% my $js_prefix = $r->dir_config('NetdotPath') . "java_script";
% for my $script ( qw(dynamic_list select jsrsClient) ){
  <script language="JavaScript" src="<% $js_prefix %>/<% $script %>.js"></script>
% }
  <body class="bodytag">
%}

<div class="container">
    <div class="containerhead">
        <% $title %>
    </div>
    <div class="containerbody">
   
      <form name="netdotform" action="edit.html" method="POST" enctype="multipart/form-data">
      <input type="hidden" name="showheader" value="<% $showheader %>"> 
      <input type="hidden" name="select_id" value="<% $select_id %>">
      <input type="hidden" name="selected" value="<% $selected %>">
      <input type="hidden" name="dowindow" value="<% $dowindow %>">
%     if( $id ) {
%         $m->comp('form.mhtml', table=>$table, id=>$id, view=>$view, dowindow=>$dowindow);
          <br>
          <input name="submit" type="submit" value="Update">
%     }else{
%       $m->comp('form.mhtml', table=>$table, session=>\%args, dowindow=>$dowindow);
        <br>
        <input name="submit" type="submit" value="Insert">
%     }
%     if ( $dowindow ){
	<input name="cancel" value="Cancel" onClick="window.close()" type="button">
%     }else{
    	<input name="cancel" value="Cancel" onClick="history.go(-1)" type="button">
%     }
      </form>
    </div>
</div>

% if ( $showheader ){
    </div>
% }else{
  </body>
</html>
% }

</%def>


% ########################################################
% # This subcomponent shows an intermediate window
% # just after an object has been created in a detached 
% # window.  The javascript code inserts the new object's
% # id and label in the caller window's form.
% ########################################################

<%def .show_inserted>
<%args>
$table
$id
$select_id  => undef
$selected   => undef
$showheader => undef
$dowindow   => undef
</%args>
<%init>
use URI::Escape;

my ( $obj, $lbl );
$obj = $table->retrieve($id);
$lbl = $obj->get_label;

</%init>
% my $onload_action = uri_escape("addandclose()", "[^A-Za-z0-9\-_.!~*'()]");

%if ( ! $showheader ){
%	$m->clear_buffer;
<html>
  <head>
      <link rel="stylesheet" href="<% $r->dir_config('NetdotPath') %>css/style.css" type="text/css">
  </head>      
% my $js_prefix = $r->dir_config('NetdotPath') . "java_script";
% for my $script ( qw(dynamic_list select jsrsClient) ){
  <script language="JavaScript" src="<% $js_prefix %>/<% $script %>.js"></script>
% }
  <body class="bodytag">

%}

<script language="javascript">
<!--
    function addandclose() {
	insertOption('<% $select_id %>', '<% $lbl %>', '<% $id %>', '<% $selected %>'); 
	window.close();
    }
-->
</script>

<div class="container">
    <div class="containerhead">
    OK
    </div>
    <div class="containerbody">
    <br>
    New <% $table %>: <% $lbl %> inserted.
    <br>
    <center>
    <a class="hand" onClick="<% $onload_action %>">[close]</a>
    </center>
    </div>
</div>

% if ( ! $showheader ){
  </body>
</html>
% }

</%def>


