#
# EMG perl DLL connector for sending via Hypermedia HTTP API
# $Change: 43222 $
#

use strict;
use Data::Dumper;
use POSIX qw(strftime);

my $debug = 1;
my $logfile = "/tmp/hm-send.log";

sub driver_encodemessage {
        my ($ci, $arg) = @_;
        my $first = ${$arg}{'first'};
        if ($first < 1) {
		my $resp = ${$arg}{'data'};

                ${$arg}{'data'} = "";

		if($debug) {
			dolog("resp=$resp");
		}
		if($resp ne 'PROCEEDING') {
			dolog("error: $resp");
                	${$arg}{'error'} = 1;
                	${$arg}{'errortext'} = $resp;
			return 2; # ERROR
		}
                return 0; # DONE
        }

        my $mess = ${$arg}{'message'};

	my $server_password = '';
	my $cnote = ${$ci}{'note'};
	if($cnote =~ /^HM:/) {
		$server_password = (split(':', $cnote))[1];
	}

	my $msg = unpack("H*", ${$mess}{'message'});
	my $unicode = 0;
	my $charcode = ${$mess}{'charcode'};
		dolog(Dumper($mess));
	if($charcode == 4) {
		$unicode = 1;
	}
	my $emg_id = ${$mess}{'id'};
	my $destaddr = ${$mess}{'destaddr'};
	my $data = "server_password=$server_password&number=$destaddr&msg=$msg&msg_id=$emg_id&unicode=$unicode";

	if($debug) {
		dolog("data=$data");
	}

        ${$arg}{'data'} = $data;
        ${$arg}{'flags'} = 1;   # breakable

        return 1;       # continue
}

sub dolog {
        my $str = shift;
	my $ts = strftime("%Y-%m-%d %H:%M:%S", localtime);
        open(OUT, ">>$logfile");
        print OUT "$ts $str\n";
        close(OUT);
}

1;
