#!/usr/bin/perl
#
# SPDX-License-Identifier: AGPL-3.0-or-later
# Copyright (c) Rainer Gümpelein, TeilRad GmbH
#
#get tracking by
#Ilockit trips by Ilockit cloud
#
#Example
#./src/scripts/Ilockit_trackingcloud.pl shareedms-operator get_tripsum 155884
#
#
#
use vars qw($syshost);

BEGIN {
  $syshost = $ARGV[0] || die;
}

use lib "/var/www/copri-bike/$syshost/src";
use strict;
use warnings;
use POSIX;
use CGI;
use Lib::Config;
use JSON;
use LWP::UserAgent;
use DateTime;
use Time::Piece;
use Mod::DBtank;
use Data::Dumper;

my $q = new CGI;
my $dbt = new DBtank;
my $cf = new Config;
my %varenv = $cf->envonline($syshost);
my $lang = "de";
my $now_dt = strftime "%Y-%m-%d %H:%M:%S", localtime;

my $api_file = "/var/www/copri4/shareeconf/apikeys.cfg";
my $aconf = Config::General->new($api_file);
my %apikeyconf = $aconf->getall;
#print "---> " . $apikeyconf{Ilockitcloud}->{username} . "\n";

my $ua = LWP::UserAgent->new;
$ua->agent("sharee APIclient");
$ua->credentials( 'tracking.ilockit.bike:443', 'api', "$apikeyconf{Ilockitcloud}->{username}", "$apikeyconf{Ilockitcloud}->{passwd}");

my $json = JSON->new->allow_nonref;
my $response_in = {};
my $dbh = "";
my $owner = 183;

my $todo = $ARGV[1];
#my $deviceId = $ARGV[2] || "";
my $pos_id = $ARGV[2] || "";
my $sleep = $ARGV[3] || "";
  
open(FILE,">>$varenv{logdir}/Ilockit_tracking.log");
print FILE "\n\n*** $now_dt\n";

#utc to localtime
sub localizedtime {
 my $date = shift;

 $date =~ s/\..*$//;
 my $time = Time::Piece->strptime($date, "%Y-%m-%dT%H:%M:%S");
 #print $time->datetime . "\n";#GMT alias Zulu
 $time = localtime($time->epoch);#epoch
 #print $time->datetime . "\n";#localized date time
 #
 return $time->datetime;
}

#localtime to utc
#my $now = strftime "%Y-%m-%dT%H:%M:%S", localtime;
#utctime($now);
#exit;
#
sub utctime {
 my $date = shift;
 my $latency = shift || 0;

 $date =~ s/\..*$//;
 $date =~ s/\+\d+$//;
 print FILE "requested datetime: " . $date . "\n";
 my $time = Time::Piece->strptime($date, "%Y-%m-%dT%H:%M:%S");
 print FILE "localtime: " . $time->datetime . "\n";#localtime
 my $utc_epoch = $time->epoch;
 $utc_epoch -= 2*60*60;# -2 std (Sommerzeit)
 #$utc_epoch -= 1*60*60;# -1 std (Winterzeit)
 $utc_epoch += $latency;
 $time = gmtime($utc_epoch);#epoch
 print FILE "utctime: " . $time->datetime . "\n";#utc zulu date time
 #
 return $time->datetime;
}

#get pos in contenttranspo
sub get_pos {
 my $id = shift;
 my $pref = {
        table  => "contenttranspos",
        fetch  => "one",
	c_id  => "$id",
 };
 my $record = $dbt->fetch_tablerecord($dbh,$pref);
 return $record;
}



if($todo eq "get_tripsum" && $pos_id){
  print FILE "trying $todo && $pos_id | sleep $sleep" . "\n";
  sleep $sleep if($sleep);
  my $rows = &get_tripsum($pos_id);
  print FILE "got rows $rows" . "\n";
}else{
  print FILE "failure: $todo && $pos_id" . "\n";
}

sub get_tripsum {
 my $pos_id = shift;
 my $ctpos = get_pos($pos_id);
 
 #TEST
 #$ctpos->{int13} = 8385;
 #$ctpos->{start_time} = "2021-10-04 08:12:29";
 #$ctpos->{end_time} = "2021-10-04 17:35:49";

 #GET /api/reports/summary?groupId=95&amp; from=2021-07-17T18:30:00Z&amp; to=2021-07-20T18:30:00Z
 my $endpoint = "https://tracking.ilockit.bike/api/reports/summary";

 #GET /api/reports/trips?groupId=95&amp; from=2020-07-17T18:30:00Z&amp; to=2021-07-20T18:30:00Z
 #my $endpoint = "https://tracking.ilockit.bike/api/reports/trips";
 #my $rest = "groupId=95\&from=$oneday\&to=$today"; 
 #my $rest = "deviceId=6574\&from=$oneday\&to=$today"; 
 #
 my $rows = 0;
 if($ctpos->{int13}){
   #start_time
   $ctpos->{start_time} =~ s/\..*$//;
   my $start_time = $ctpos->{start_time};
   $start_time =~ s/\s/T/;
   my $utc_start_time = utctime($start_time,"0");
   $utc_start_time .= "Z";

   #end_time
   #my $end_time = strftime "%Y-%m-%dT%H:%M:%S", localtime;
   $ctpos->{end_time}  =~ s/\..*$//;
   my $end_time = $ctpos->{end_time};
   $end_time =~ s/\s/T/;
   #add 5 minutes, 300sec for latency
   my $utc_end_time = utctime($end_time,"+300");
   $utc_end_time .= "Z";

   my $rest = "deviceId=$ctpos->{int13}\&from=$utc_start_time\&to=$utc_end_time";
   #my $rest = "deviceId=$ctpos->{int13}\&from=2021-11-03T07:50:00Z\&to=2021-11-03T11:00:00Z";

   my $ret_json = fetch_ilockit_cloud("","$endpoint",$rest);
   $response_in = decode_json($ret_json);
   print FILE "ilockit get_tripsum response_in:" . Dumper($response_in) . "\n";

   if(1==1){
    my $update_pos = {
          table   =>      "contenttranspos",
	  int26	  =>	0,
    };
    #disabled to keep real rental owner id
    #owner   =>      $owner,
    #mtime   =>      "now()",

    foreach my $resp (@{ $response_in }) {
     if($ctpos->{int13} eq $resp->{deviceId}){
	print FILE "device Id: $resp->{deviceId}" . "\n";
	print FILE "distance: $resp->{distance}" . "\n";
	if($resp->{distance} && $resp->{distance} > 0){
	 #my $distance = $resp->{distance} / 1000 * 1.60934; #distance in Meilen
	 my $distance = 0;
	 $distance = $resp->{distance} / 1000;
	 $distance = sprintf('%.2f', $distance);
  	 $update_pos->{int26} = $distance if($distance < 1000);
	}
     }
    }
    $rows = $dbt->update_record($dbh,$update_pos,$ctpos) if($ctpos->{c_id} && $update_pos->{int26});
   }
 }else{
   print FILE "failure: There is no contenttranspo deviceId int13: $ctpos->{int13}"  . "\n";
 }
 return $rows;
}#end if($todo eq "get_tripsum"){


#ilockit http request
sub fetch_ilockit_cloud {
 my $self = shift;
 my $ilockitserver = shift || "";
 my $rest = shift || "";
 my $ilockit_request = "$ilockitserver?$rest";

 print FILE "fetch_ >> " . $ilockit_request . "\n";

 my $req = HTTP::Request->new(GET => "$ilockit_request");
 $req->content_type('application/json');
 $req->content($rest);

 my $res = $ua->request($req);
 if ($res->is_success) {
  #print $res->content;
  return $res->content;
  print $res->status_line, "\n";
 }else {
  print $res->status_line, "\n";
 }
}

close(FILE);
1;
