%# BEGIN BPS TAGGED BLOCK {{{
%#
%# COPYRIGHT:
%#
%# This software is Copyright (c) 1996-2014 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 }}}
%# REST/1.0/Forms/ticket/comment
%#
<%ARGS>
$id
%changes
</%ARGS> 
<%INIT>
use MIME::Entity;
use RT::Interface::REST;

# ----------------------------------------------------------------------- IDD START 
use File::Copy;
use File::Basename;
# ----------------------------------------------------------------------- IDD END

$RT::Logger->debug("Got ticket id=$id for comment");
$RT::Logger->debug("Got args @{[keys(%changes)]}.");

my $ticket = RT::Ticket->new($session{CurrentUser});
my ($c, $o, $k, $e) = ("", [], {}, 0);

# http://.../REST/1.0/ticket/1/comment
$ticket->Load($id);
if (!$ticket->Id) {
    $e = 1;
    $c = "# Ticket $id does not exist.";
    goto OUTPUT;
}

my $action;
($action = $changes{Action}) =~ s/^(.)(.*)$/\U$1\L$2\E/;
unless ($action =~ /^(?:Comment|Correspond)$/) {
    $e = 1;
    $c = "# Invalid action: `$action'.";
    goto OUTPUT;
}

my $text = $changes{Text};
my @atts = @{ vsplit($changes{Attachment}) };

if (!$changes{Text} && @atts == 0) {
    $e = 1;
    $c = "# Empty comment with no attachments submitted.";
    goto OUTPUT;
}

my $ent = MIME::Entity->build(
    Type => "multipart/mixed",
    'X-RT-Interface' => 'REST',
);
$ent->attach(
    Type    => $changes{'Content-Type'} || 'text/plain',
    Charset => "UTF-8",
    Data    => Encode::encode("UTF-8", $changes{Text} ),
) if $changes{Text};


{
    my ($status, $msg) = process_attachments($ent, @atts);
    unless ( $status ) {
        $e = 1;
        $c = "# $msg";
        goto OUTPUT;
    }
}

unless ($ticket->CurrentUserHasRight('ModifyTicket') ||
        ($action eq "Comment" &&
         $ticket->CurrentUserHasRight("CommentOnTicket")) ||
        ($action eq "Correspond" &&
         $ticket->CurrentUserHasRight("ReplyToTicket")))
{
    $e = 1;
    $c = "# You are not allowed to $action on ticket $id.";
    goto OUTPUT;
}


# ----------------------------------------------------------------------- IDD START        
$RT::Logger->debug( " Entro en comment: " . Data::Dumper::Dumper( %changes ) );
        
# Se camufla el parámetro LUCIA en el Cc. 
if( $changes{Cc} ){
   	my @Cc = split(', ', $changes{Cc});
   	my $first = shift @Cc;
        	
   	if( $first eq 'luciaexternal' ){
   		$RT::Logger->debug( " Lucia request. It will be stored into database." );
   		my $requestId = shift @Cc;
   		my $vRest = shift @Cc;
      		
   		my $requestUser = $session{CurrentUser}->Name;
       
   		# En comment/correspond se almacena la petición salvo que haya una petición con el mismo ID para dicho ticket
   		my $driver = RT->Config->Get('DatabaseType');
		my $database = RT->Config->Get('LuciaSyncDatabase');
		my $userid = RT->Config->Get('LuciaSyncUser');
		my $password = RT->Config->Get('LuciaSyncPassword');
		my $dsn = "DBI:$driver:database=$database";
				      
		my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;
		# Blob read size
		$dbh->{LongReadLen} = 512 * 1024;
				      
		# Establish database codification to avoid blob corruption
		my $sth = $dbh->prepare("SET NAMES utf8;");
		$sth->execute() or die $DBI::errstr;
		$sth->finish();
				
		try {
			# Control de duplicados
			my $query = "SELECT * FROM `$database`.`incoming_requests` 
							WHERE `sourcerequestid` = ? AND `ticketid` = ? AND `user` = ?";
			$sth = $dbh->prepare( $query ) or die "Unable to prepare $query" . $dbh->errstr;
			my $numrows = $sth->execute( $requestId, $changes{Ticket}, $requestUser ) or die $DBI::errstr;
			$sth->finish();
			    
			if( $numrows == 0) {
				# Almacenamiento de petición
				$RT::Logger->debug( "Storing request..." );
				
				my @filenames = ();
				if( $changes{Attachment} ){
					my $att_dir = RT->Config->Get('LuciaAttachDir');
					my $count = 1;
					for my $attachment ( @atts ){
						$RT::Logger->debug( "\n -> Procesamos el adjunto: " . $attachment );
						
						my $tmp_file = $ent->{'ME_Parts'}[$count]->{'ME_Bodyhandle'}->{'MB_Path'};
						my $file_name = fileparse($attachment);
						
						# Se crea el fichero dentro de una carpeta con el epoch para evitar sobreescribir archivos con mismo nombre
						my $dirname = $att_dir . "/" .  time;
						mkdir $dirname unless -d $dirname;
						my $mode = 0775;
						chmod $mode, $dirname;
						my $new_name = $dirname . '/'. $file_name;
						
						$RT::Logger->debug( "\n -> Copia: " . $tmp_file . " - > " . $new_name );
						copy($tmp_file, $new_name) or $RT::Logger->error("Copy failed");
						push @filenames, $new_name;
						$count++;
					}
				}
						
				my $insert_query = "INSERT INTO `$database`.`incoming_requests` (`sourcerequestid`, `action`, `ticketid`, `text`, `user`, `date`, `vrest`)
									 VALUES (?, ?, ?, ?, ?, NOW(), ?)";
				$sth = $dbh->prepare( $insert_query );
				if( @filenames ){
					my $filenames_str = join( "\n", @filenames );
					$numrows = $sth->execute( $requestId, 'attachment', $changes{Ticket}, $filenames_str, $requestUser, $vRest ) or die $DBI::errstr;
				} else {
					$numrows = $sth->execute( $requestId, $changes{Action}, $changes{Ticket}, $changes{Text}, $requestUser, $vRest ) or die $DBI::errstr;
				}
				$sth->finish();
				$RT::Logger->debug( "Request stored." );
				$c = '# Request stored';
				
			} else {
				$RT::Logger->info( "Request already present." );
				$c = '# Request already present';
			}
		
		} finally {
			$dbh->disconnect;
		};
       	
  		goto OUTPUT;
  		
   	} else {
   		$RT::Logger->debug( " Internal request. It will be processed." );
   		unshift $changes{Cc}, $first;
   	}
} else {
   	$RT::Logger->debug( " Internal request. It will be processed." );
}
        
# ----------------------------------------------------------------------- IDD END 

my $cc = join ", ", @{ vsplit($changes{Cc}) };
my $bcc = join ", ", @{ vsplit($changes{Bcc}) };
my ($n, $s) = $ticket->$action(MIMEObj => $ent,
                               CcMessageTo => $cc,
                               BccMessageTo => $bcc,
                               TimeTaken => $changes{TimeWorked} || 0);
$c = "# ".$s;
if ($changes{Status}) {
   my  ($status_n, $status_s) = $ticket->SetStatus($changes{'Status'} );   
  $c .= "\n# ".$status_s;
}

OUTPUT:

return [ $c, $o, $k, $e ];
</%INIT>