#!/usr/bin/perl
##############################################################################
#
# RemotePlusSampleClient
#
# Usage:
#
#   RemotePlusSampleClient.pl <user> <password> [<url>]
#
# Copyright (c) 2014 Interactive Data 
#
##############################################################################

use strict;
use LWP::UserAgent;
use URI::Escape;
require HTTP::Request;
# NOTE FOR PROGRAMMERS: Make sure that the Text::CSV library is installed!
use Text::CSV;

my $default_url = "https://rplus.intdata.com/cgi/nph-rplus";

#
# Check the command line arguments
#
if (@ARGV != 2 and @ARGV != 3) {
   
   # Show the usage

   print "Usage: RemotePlusSampleClient.pl <user> <password> [<url>]\n\n";
   print "The default URL is $default_url\n";
   exit 0;

}

my $user = shift;
my $password = shift;

my $url = shift;

if (!$url) {
    $url = $default_url;
}

# Show the initial salutation
print qq(Welcome to RemotePlus. Type "help" for help, and "exit" or "quit" to quit\n);
print qq(To specify a list file name, place the filename in curly braces like get,{Equity.lst},des1\n\n);
print "rplus> ";

# Create a buffer to hold commands as they are typed
my $buffer = "";

#
# Enter the 'main loop'
#
while (my $line = <STDIN>) {

    chomp $line;

    # If the line ends with a backslash, the command should continue on
    # the next line.
    if ($line =~ /^(.*)\\$/) {

        # add this line to the buffer (without the backslash)

        $buffer = "$buffer$1";
    } else {

        # add this line to the buffer, and process the command
        $buffer = "$buffer$line";
        processCommand($buffer);

        $buffer = "";
    }

    print "rplus> ";
}

exit 0;

##############################################################################
#
# processCommand(command) - process a user command (i.e. evaluate it and
#                           send it to RemotePlus, if necessary).
#
##############################################################################
sub processCommand {

    my $command = shift;


    if ($command =~ /^\s*help\b/) {

        showHelp();

    } elsif ($command =~ /^\s*exit\b/ or
             $command =~ /^\s*quit\b/) {

        exit 0;

    } else {

        my $userAgent = new LWP::UserAgent;
        my $request = new HTTP::Request 'POST', $url;
     
        # Check for {} as file designator
        # NOTE FOR PROGRAMMERS: There is nothing special about using {curly braces}.
        # It is just a convenient method of designating a filename in our example.
        while ($command =~ /{([^}]+)}/g) {
           my $filename = $1;
           if (open my $listfile,'<',$filename) {
              my $list = join(',',map { chomp;$_ } <$listfile>);
              $command =~ s/{$filename}/($list)/;
              close $listfile;
           } else {
             print "Cannot open listfile '$1': $!. Please try again.\n";
             return;
           }
        }

        my $encodedCommand = uri_escape($command,"\@\,");

        # Formulate the request

        $request->content('Request=' . 
                          $encodedCommand . 
                          '&Done=flag');
        $request->authorization_basic($user, $password);

        # Send the request

        my $result = $userAgent->request($request);
          

	my $csv = Text::CSV->new ( { binary => 1 } ) or die "Cannot use CSV: ".Text::CSV->error_diag ();
        my @rplusdata = split("\n",$result->content); 

        print "Raw results:\n";
        print $result->content;
        print "-----------\n\n"; 
        print "Split by commas, then re-combined with pipes:\n";
        for my $outputline (@rplusdata) { 
           $csv->parse($outputline);
           my @fields = $csv->fields();
         
           print join("|",@fields)."\n";
        }

        
    }
}

##############################################################################
#
# showHelp() - show the help text
#
##############################################################################
sub showHelp {

    print "Enter a RemotePlus command, e.g.\n\n";

    print "\trplus> get,ibm,(cusp,prc),20020701,20020911,titles=short\n\n";

    print 
      "If you wish to continue a command onto another line, you may place a\n";
    print
      "backslash (\\) at the end of the line, e.g.\n\n";

    print "\trplus> get,ibm,(cusp,prc,prcadata),\\\n";
    print "\t> 20020701,20020911,titles=short,dateform=ymd\n";
}

