package Lyrics::Fetcher::LyricsTranslate;

use 5.014000;
use strict;
use warnings;

use HTML::TreeBuilder;
use HTTP::Tiny;

our $VERSION = '0.001';
our $BASE_URL = 'http://lyricstranslate.com';
# 0 means any language, 328 means English
our $URL_FORMAT = "$BASE_URL/en/translations/0/328/%s/%s/none";

my $ht = HTTP::Tiny->new(agent => "Lyrics-Fetcher-LyricsTranslate/$VERSION ");

sub fetch {
	my ($self, $artist, $song) = @_;
	$Lyrics::Fetcher::Error = 'OK';
	my $url = sprintf $URL_FORMAT, $artist, $song;
	my $response = $ht->get($url);
	unless ($response->{success}) {
		$Lyrics::Fetcher::Error = 'Search request failed: ' . $response->{reason};
		return
	}
	my $tree = HTML::TreeBuilder->new_from_content($response->{content});
	# First result would be the link to the artist, so we get the second one
	my (undef, $result) = $tree->look_down(class => 'ltsearch-translatenameoriginal');
	unless ($result) {
		$Lyrics::Fetcher::Error = 'Lyrics not found';
	}
	$response = $ht->get($BASE_URL . $result->find('a')->attr('href'));
	unless ($response->{success}) {
		$Lyrics::Fetcher::Error = 'Lyrics request failed: ' . $response->{reason};
		return
	}
	$tree = HTML::TreeBuilder->new_from_content($response->{content});
	my $node = $tree->look_down(class => qr/\btranslate-node-text\b/);
	my $ltf = $node->look_down(class => qr/\bltf\b/);
	my @pars = $ltf->look_down(class => 'par');
	join "\n", map {
		join '', map { $_->as_trimmed_text . "\n" } $_->content_list
	} @pars
}

1;
__END__

=encoding utf-8

=head1 NAME

Lyrics::Fetcher::LyricsTranslate - Get lyrics from lyricstranslate.com

=head1 SYNOPSIS

  # This module should be used directly
  use Lyrics::Fetcher::LyricsTranslate;
  print Lyrics::Fetcher::LyricsTranslate->fetch('Lyube', 'Kombat');

  # Can also be used via Lyrics::Fetcher but produces ugly output
  use Lyrics::Fetcher;
  print Lyrics::Fetcher->fetch('Lyube', 'Kombat', 'LyricsTranslate');

=head1 DESCRIPTION

This module tries to get translated lyrics from
L<http://lyricstranslate.com>. It does a search for a translation of
the given artist and song title from any language to English, and
returns the contents of the first result found.

This is a very basic implementation of the concept and it should be
improved in future versions (for example supporting multiple
destination languages).

It is recommended to use the module directly, as using it via
L<Lyrics::Fetcher> loses empty lines between parahraphs.

=head1 SEE ALSO

L<Lyrics::Fetcher>

=head1 AUTHOR

Marius Gavrilescu, E<lt>marius@ieval.roE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2016 by Marius Gavrilescu

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.24.0 or,
at your option, any later version of Perl 5 you may have available.


=cut
