#/usr/bin/perl

use strict;
use warnings;

# 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 4034
# 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,$ppi) = ('','','','','','','');
  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,<CertificationNumber>(.*)</CertificationNumber>,);
    $ppi = $1 if($l =~ m,<value>product_pictures/(.*)\.(.*)</value>,);

  }
  close(FH);
  if($pic ne $ppi) {
    printf "$path: CertificationNumern:$pic ne ProductPicture:$ppi\n";
    # just to see new problems with pictures
  }
  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;
  }
  # There is sometimes 0x0x in the XML, see
  # https://products.z-wavealliance.org/products/1694
  $mi =~s/0x/00/;
  $pti=~s/0x/00/;
  $pi =~s/0x/00/;
  printf OF "%s-%s-%s,%s,%s,%s\n", $mi,$pti,$pi,$fn,$pic,$bn;
}
closedir(DIRH);
close(OF);