#!/usr/bin/perl

use strict;
use warnings;
use FindBin qw( $Bin );
use lib "$Bin/../../lib";
use Data::Dumper;
use Spreadsheet::ParseExcel::Simple;
use Text::CSV_XS;
use App::POS::Utils qw( fix_encoding trim );
use Encode qw( encode decode );

my $xls_file = shift || die "Usage: $0 <xls_file>\n";

my $csv_file = $xls_file . ".csv";

my $xls = Spreadsheet::ParseExcel::Simple->read($xls_file) or die "error parsing xls $xls_file: $!\n";
my $csv = Text::CSV_XS->new({ sep_char => ',' });

open(F, "> $csv_file") or die "Can't write $csv_file: $!\n";
my $c = 0;

foreach my $sheet ($xls->sheets) {
  my $count = 0;

  while ($sheet->has_data) {
    my @d = $sheet->next_row;

    my $line = "";

    for (my $i=0; $i<scalar @d; $i++) {
      my $v = $d[$i];
      $v = trim($v);
      $v =~ s/",//g;

      eval {
        $v = encode("utf8", $v);
      };

      if ($@) {
        $v = "";
      }

      $line .= $v.",";
    }

    chop($line);
    print F "$line\n";

    #my $status = $csv->combine(@d);
    ##my $str = fix_encoding($csv->string());
    #my $str = $csv->string();
    #print STDERR "### $str ($c)\n";
    #print F "$str\n";
    $c++;
  }
}

close(F);
unlink $csv_file unless $c > 0;
