#!/usr/bin/perl

use strict;
use LWP::Simple;
use Data::Dumper;
use JSON;
$|=1;

die "$0 <search param>" unless $ARGV[0];
my $ref;
my $offset;
my $req;
while(1) {
  $req = "";
  my $root_url = "http://next.lala.com/api/SearchUtils/search/v19.110.0-24?Q=$ARGV[0]&sortKey=relevance&sortDir=desc&Nb=100&Sk=$offset&webSrc=lala";
  my $content = get $root_url;
  $content =~ s/new Date\((\d+)\)/$1/g;
  $ref = from_json($content, {utf8 => 1});

  my $num = 0;
  foreach (@{$ref->{data}->{songs}->{list}}) {
    next if $_->{playType} eq "Sample";
    print "$num : $_->{artist} - $_->{title}\n";
    $num++;
  }

  print "Download which? > ";
  chomp($req = <STDIN>);
  if ($req =~ /n/) {
    $offset+=100;
    next;
  }
  if ($req =~ /p/) {
    $offset-=100;
    $offset=0 if $offset<0;
    next;
  }
  if ($req !~ /\d+/ or $req < 0 or $req > $num) {
    print "Invalid!\n";
    next;
  }
  last;
}
my $download_url = "http://next.lala.com/api/Player/getTrackUrls?flash=true&webSrc=lala&widgetId=LalaHeadlessPlayer&T=" . $ref->{data}->{songs}->{list}->[$req]->{playToken};
my $play_url = get $download_url;
my $play_ref = from_json($play_url);
my $download_link = $play_ref->{data}->[0]->{url};
print "Getting: $download_link\n";
my $filename = $ref->{data}->{songs}->{list}->[$req]->{artist} ."-" . $ref->{data}->{songs}->{list}->[$req]->{title} . ".mp3";
print "Downloading to $filename\n";
system("curl -o '$filename' $download_link");
