#!perl 

#export to csv with
##influx -username admin -password 'mypw' -database 'iobroker' -execute 'select * from "javascript.0.Volkszaehler.AKTUELLER_STROMFLUSS"' -format csv > stromfluss.csv
#need to convert csv export to line protocol for re-inserting
# load with  influx -username admin -password 'mypw' -database 'iobroker' -import -path=AKTUELLER_Bezug.csv
#
#name,time,ack,from,q,value
#javascript.0.Volkszaehler.AKTUELLER_STROMFLUSS,1600421947419000000,false,system.adapter.influxdb.0,0,-3953.696
#treasures,captain_id=dread_pirate_roberts value=801 1439856000
#
#javascript.0.Volkszaehler.AKTUELLER_STROMFLUSS,ack=false,from=system.adapter.influxdb.0,q=0 value=-3953.696 1600421947419000000
#dummy,ack=false,from=system.adapter.influxdb.0,q=0 value=-3953.696 1600421947419000000

use strict;
use warnings;

my $filename = 'stromfluss.csv';
my $filename_m1 = 'AKTUELLER_Bezug.csv';
my $filename_m2 = 'AKTUELLE_Lieferung.csv';
open(my $fh, '<:encoding(UTF-8)', $filename) or die "Could not open file '$filename' $!";
open(my $fhm1, '>:encoding(UTF-8)', $filename_m1) or die "Could not open file '$filename_m1' $!";
open(my $fhm2, '>:encoding(UTF-8)', $filename_m2) or die "Could not open file '$filename_m2' $!";

#name,time,ack,from,q,value
#javascript.0.Volkszaehler.AKTUELLER_STROMFLUSS,1600421947419000000,false,system.adapter.influxdb.0,0,-3953.696

my ($dest_measurement1, $dest_measurement2)=('javascript.0.Volkszaehler.AKTUELLER_Bezug','javascript.0.Volkszaehler.AKTUELLE_Lieferung');

print $fhm1 "# DML\n";
print $fhm1 "# CONTEXT-DATABASE: iobroker\n"; #adjust to your own db
print $fhm2 "# DML\n";
print $fhm2 "# CONTEXT-DATABASE: iobroker\n"; #adjust to your own db


while (my $row = <$fh>) 
{
  chomp $row;
  next if $row=~/name/; #skip header row for line protocol
  my ($m1,$m2)=(0,0);
  print "$row\n";
  my @row= split /,/, $row;
  if ($row[5]!~/^-/) #not sure it gets identified as number
  {
    $m2=0;
    $m1=$row[5];
  }
  elsif ($row[5]=~/^0\s*$/)
  {
    $m1=0;
    $m2=0;
  }
  else #negative, means we sell power
  {
    #$m2=abs($row[5]);
    $m2=$row[5];
    $m2=~s/-//; #remove -
    $m1=0;
  }

  #print $fhm1 "$dest_measurement1,$row[1],$row[2],$row[3],$row[4],$m1\n";
  #print "$dest_measurement1,$row[1],$row[2],$row[3],$row[4],$m1\n";
  #print $fhm2 "$dest_measurement2,$row[1],$row[2],$row[3],$row[4],$m2\n";
  #print "$dest_measurement2,$row[1],$row[2],$row[3],$row[4],$m2\n";
  #
  #javascript.0.Volkszaehler.AKTUELLER_STROMFLUSS,ack=false,from=system.adapter.influxdb.0,q=0 value=-3953.696 1600421947419000000
  print $fhm1 "$dest_measurement1,ack=$row[2],from=$row[3],q=$row[4] value=$m1 $row[1]\n";
  print $fhm2 "$dest_measurement2,ack=$row[2],from=$row[3],q=$row[4] value=$m2 $row[1]\n";
}

close $fh;
close $fhm1;
close $fhm2;
