#/usr/bin/perl

# Creates the FHEM file from the raw data

# Usage: zwavealliance.images.parse downloaddir
# Downloaddir is filled with the following script:
# i=1
# while test $i -lt 3000
# do
#   echo $i
#   wget -O $i -q http://products.z-wavealliance.org/products/$i/XML
#   i=`expr $i + 1`
# done

die("Usage: zwavealliance.images.parse downloaddir\n") if(int(@ARGV) != 1);

open(OF, ">zwave_alliancelinks.csv");
opendir(DIRH, $ARGV[0]) || die("Cant open $ARGV[0]\n");
my @files;
while(my $fn = readdir(DIRH)) {
  push @files, $fn;
}

for my $fn (sort { $a <=> $b } @files) {
  my $path = "$ARGV[0]/$fn";
  next if (! -f $path);
  print("$fn\n");
  open(FH, $path) || die("Cant open $path\n");
  my ($bn,$mi,$pti,$pi,$pic,$em) = ('','','','','','');
  while(my $l = <FH>) {
    chomp($l);

    $em  = 'empty' if($l =~ m,<h2>Oh no ... we encountered an error!</h2>,);
    $bn  = $1 if($l =~ m,<Brand>(.*)</Brand>,);
    $mi  = $1 if($l =~ m,<ManufacturerId>0x(....)</ManufacturerId>,);
    $pti = $1 if($l =~ m,<ProductTypeId>0x(....)</ProductTypeId>,);
    $pi  = $1 if($l =~ m,<ProductId>0x(....)</ProductId>,);
    $pic = $1 if($l =~ m,<Image>.*productName=(.*)</Image>,);

  }
  close(FH);
  if($em eq 'empty') {
    printf "No data for $fn, deleting the file\n";
    # in the hope that somebody will fix the file
    unlink("$ARGV[0]/$fn");
    next;
  }
  if($mi eq '' || $pti eq '' || $pi eq '') {
    printf "Missing parameters for $fn: Brand:$bn, ManufId:$mi, ProductType:$pti, ProductId:$pi, deleting the file\n";
    # in the hope that somebody will fix the file
    unlink("$ARGV[0]/$fn");
    next;
  }
  printf OF "%s-%s-%s,%s,%s,%s\n", $mi,$pti,$pi,$fn,$pic,$bn;
}
closedir(DIRH);
close(OF);
