#!/usr/bin/perl

use strict;
use warnings;
use FindBin qw( $Bin );
use Data::Dumper;
use File::Find qw( find );
use JSON::XS;
use URI::Escape;

my $NAME = shift;
die "Usage: $0 <playlist name>\n" unless defined $NAME;

my $MACHINE_ID=`$Bin/machine_id`;
my $HAS_NETWORK=`$Bin/has_network`;
chop($HAS_NETWORK);

if ($HAS_NETWORK ne 'YES') {
  die "No network connectivity, aborting...\n";
}

my $actual_files = &collect_files();
print STDERR "Actual files:\n";
print STDERR Dumper($actual_files);

my $had_files = 0;

#if (scalar @$actual_files) {
  my $json_str = encode_json($actual_files);
  my $tmp_file1 = "/tmp/".$$."_".int(rand(1000000)).".post";
  my $tmp_file2 = "/tmp/".$$."_".int(rand(1000000)).".post";
  open(F, "> $tmp_file1");
  #my $tt = "machine_id=$MACHINE_ID&playlist=$NAME&files=".uri_escape($json_str);
  #print STDERR $tt."\n";
  #exit;
  print F "machine_id=$MACHINE_ID&playlist=$NAME&files=".uri_escape($json_str)."\n";
  close(F);
  system("wget -o /dev/null --timeout=5 --post-file $tmp_file1 -q -O $tmp_file2 \"http://releases.ptcert.com/api/machines/music/playlist_sync\"");
  unlink($tmp_file1);
  open(F, "< $tmp_file2");
  local $/ = undef;
  my $json = <F>;
  close(F);
  unlink($tmp_file2);

  print STDERR "### $json\n";

  if ($json) {
    my $ref = &decode_json($json);
    print STDERR Dumper($ref);
    $ref->{to_remove} ||= [];
    $ref->{to_download} ||= [];

    for (@{ $ref->{to_remove} }) {
      $had_files = 1;

      print STDERR "WILL REMOVE: $_\n";
      unlink "$Bin/../music/$_";
    }

    for (@{ $ref->{to_download} }) {
      next if $_ eq '.';

      $had_files = 1;
      print STDERR "WILL DOWNLOAD: ".uri_escape($_)."\n";
      my $res = system("wget -o /dev/null --timeout=5 -O \"$Bin/../music/$_\" \"http://releases.ptcert.com/music/".$ref->{id}."/".uri_escape($ref->{playlist_name})."/".uri_escape($_)."\"");

      if ($res == 0) {
        $had_files = 1;
      }
    }
  }
#}

print STDERR "HAD_FILES: $had_files\n";

if ($had_files) {
  system("/opt/pos/common/bin/graphical_customer_display.sh 1");
}

sub collect_files {
  my $r = [];

  &find( sub {
    #return unless /mp3$/i;
    return unless -f $File::Find::name;
    return if $_ eq 'mp3playlist';
    return if $_ eq 'playlist';
    return if $_ eq 'selected_playlist.txt';

    push @$r, { path => $File::Find::dir, name => $_, size => -s $File::Find::name };
  }, ( $Bin."/../music" ) );

  return $r;
}

