#!/usr/bin/perl -w
#
# Reads CDDB info, allow modifications and send back to CDDB server
#
# $Id$
#
# Copyright B. Cornec 2009
# Provided under the GPL v2

# Syntax: see at end

use strict 'vars';
use Getopt::Long qw(:config auto_abbrev no_ignore_case);
use Data::Dumper;
use English;
use ProjectBuilder::Base;
use ProjectBuilder::Conf;
use Mail::Sendmail;
use POSIX  qw(strftime :sys_wait_h);
use Newt qw(NEWT_FLAG_WRAP NEWT_ENTRY_SCROLL NEWT_ANCHOR_LEFT :entry :textbox :macros);
use lib qw (lib);
use locale;
use CDDB_get qw( get_cddb get_discids );
use CDDB;
use Encode;

# Global variables
my %opts;					# CLI Options
my $action;					# action to realize

my @date = pb_get_date();
my $pbdate = strftime("%Y-%m-%d", @date);

=pod

=head1 NAME

CDDBeditor, read, modidy and send your CDDB contrinutions

=head1 DESCRIPTION

CDDBeditor helps you read, modidy and send your CDDB contrinutions.

=head1 SYNOPSIS

CDDBeditor [-vhmq][-t|-g]

CDDBeditor [--verbose][--help][--man][--quiet][--text|--graphic]

=head1 OPTIONS

=over 4

=item B<-v|--verbose>

Print a brief help message and exits.

=item B<-q|--quiet>

Do not print any output.

=item B<-h|--help>

Print a brief help message and exits.

=item B<--man>

Prints the manual page and exits.

=item B<-t|--text>
=item B<-g|--graphic>

Interface is either text mode or graphical mode (newt based)

=back 

=head1 ARGUMENTS

=head1 WEB SITES

The main Web site of the project is available at L<http://www.project-builder.org/>. Bug reports should be filled using the trac instance of the project at L<http://trac.project-builder.org/>.

=head1 USER MAILING LIST

None exists for the moment.

=head1 CONFIGURATION FILES

=head1 AUTHORS

The CDDBeditor team L<http://trac.project-builder.org/> lead by Bruno Cornec L<mailto:bruno@project-builder.org>.

=head1 COPYRIGHT

CDDBeditor is distributed under the GPL v2.0 license
described in the file C<COPYING> included with the distribution.

=cut

# ---------------------------------------------------------------------------

#Avoids an error from Newt
no AutoLoader;


# Initialize the syntax string

my $projver = "PBVER";
my $projrev = "PBREV";

pb_syntax_init("CDDBeditor Version $projver-$projrev\n");

GetOptions("help|?|h" => \$opts{'h'}, 
		"man" => \$opts{'man'},
		"verbose|v+" => \$opts{'v'},
		"quiet|q" => \$opts{'q'},
		"text|t" => \$opts{'t'},
		"graphic|g" => \$opts{'g'},
		"version|V=s" => \$opts{'V'},
) || pb_syntax(-1,0);

if (defined $opts{'h'}) {
	pb_syntax(0,1);
}
if (defined $opts{'man'}) {
	pb_syntax(0,2);
}
if (defined $opts{'v'}) {
	$pbdebug = $opts{'v'};
}
if (defined $opts{'q'}) {
	$pbdebug=-1;
}
pb_log_init($pbdebug, $pbLOG);


Newt::Init();
my ($ce_sl, $ce_sh) = Newt::GetScreenSize();

# String definitions
my $ce_title = "CDDBeditor";
my $ce_help = "(c) Bruno Cornec 2009 - All right reversed under the GPL v2";
my $artist_label = Newt::Label("Artist: ");
my $data_label = Newt::Label("Data: ");
my $raw_label = Newt::Label("Raw: ");
my $title_label = Newt::Label("Title: ");
my $year_label = Newt::Label("Year: ");
my $id_label = Newt::Label("Id: ");
my $genre_label = Newt::Label("Genre: ");
my $category_label = Newt::Label("Category: ");
my $info_label = Newt::Label("Info: ");
my $tr_track_label = Newt::Label("Track");
my $tr_frames_label = Newt::Label("Frames");
my $tno_label = Newt::Label("Track #:");
my $tr_title_label = Newt::Label("Title");
my $tr_author_label = Newt::Label("Author");
my $tr_length_label = Newt::Label("Length");

my $host_label = Newt::Label("Host: ");
my $port_label = Newt::Label("Port: ");
my $mode_label = Newt::Label("Mode: ");
my $dev_label = Newt::Label("Device: ");
my $proxy_label = Newt::Label("Proxy: ");
my $user_label = Newt::Label("Multi CD: ");

my $wait_label = Newt::Label("Please wait while searching ...");

# To be put in conf file
my %ce_config;
$ce_config{"CDDB_HOST"}="freedb.freedb.org";
$ce_config{"CDDB_PORT"}=80;
my %ce_cddb_mode;
$ce_cddb_mode{"0"} = "http";
$ce_cddb_mode{"1"} = "cddb";

$ce_config{"CDDB_MODE"}=$ce_cddb_mode{"0"};
$ce_config{"CD_DEVICE"}="/dev/sr0";
$ce_config{"HTTP_PROXY"}=$ENV{http_proxy} if $ENV{http_proxy};
$ce_config{"input"}=0;

# First panel for configuration parameters
Newt::Cls();
Newt::DrawRootText(ce_center_string($ce_title), 1, $ce_title);
Newt::PushHelpLine($ce_help);
Newt::Refresh();

my $flag = NEWT_ENTRY_SCROLL;
my $width = 40;
my $host_entry = Newt::Entry($width, $flag, $ce_config{"CDDB_HOST"});
$width = 5;
my $port_entry = Newt::Entry($width, $flag, $ce_config{"CDDB_PORT"});
my $mode_group;
my $proxy_entry = undef;
if ($ce_config{"CDDB_MODE"} eq $ce_cddb_mode{"0"} ) {
	$mode_group = Newt::HRadiogroup($ce_cddb_mode{"0"}, $ce_cddb_mode{"1"});
	$proxy_entry = Newt::Entry($width, $flag, $ce_config{"HTTP_PROXY"});
} else {
	$mode_group = Newt::HRadiogroup($ce_cddb_mode{"1"}, $ce_cddb_mode{"0"});
}
$width = 40;
my $dev_entry = Newt::Entry($width, $flag, $ce_config{"CD_DEVICE"});
my $user_group;
if ($ce_config{input} == 0 ) {
	$user_group = Newt::HRadiogroup('FALSE', 'TRUE');
} else {
	$user_group = Newt::HRadiogroup('TRUE', 'FALSE');
}
my $quit_button = Newt::Button("Quit");
$quit_button->Tag("Quit");
my $next_button = Newt::Button("Next");
$next_button->Tag("Next");

my $ce_panel = Newt::Panel(2, 20, "CDDBeditor Configuration");
my $flage = NEWT_ANCHOR_LEFT;
$ce_panel->Add(0, 0, $host_label);
$ce_panel->Add(1, 0, $host_entry, $flage);
$ce_panel->Add(0, 1, $port_label);
$ce_panel->Add(1, 1, $port_entry, $flage);
$ce_panel->Add(0, 2, $mode_label);
$ce_panel->Add(1, 2, $mode_group, $flage);
$ce_panel->Add(0, 3, $proxy_label);
$ce_panel->Add(1, 3, $proxy_entry, $flage);
$ce_panel->Add(0, 4, $dev_label);
$ce_panel->Add(1, 4, $dev_entry, $flage);
$ce_panel->Add(0, 5, $user_label);
$ce_panel->Add(1, 5, $user_group, $flage);
$ce_panel->Add(0, 6, $next_button);
$ce_panel->Add(1, 6, $quit_button);

Newt::Refresh();
my ($reason, $data) = $ce_panel->Run();

Newt::Cls();
exit 0 if ($data->Tag() eq "Quit");

$ce_config{"CDDB_HOST"}=$host_entry->Get();
$ce_config{"CDDB_PORT"}=$port_entry->Get();
$ce_config{"CDDB_MODE"}=$ce_cddb_mode{$mode_group->Get()};
$ce_config{"CD_DEVICE"}=$dev_entry->Get();
$ce_config{"HTTP_PROXY"}=$proxy_entry->Get();
$ce_config{"input"}=$user_group->Get();

# Components
my $reload_button = Newt::Button("Reload");
$reload_button->Tag("Reload");
my $send_button = Newt::Button("Send");
$send_button->Tag("Send");

# Entering the loop
for (my $i=0 ; ; $i++) {
	# Second panel to make user wait
	Newt::Cls();
	Newt::DrawRootText(ce_center_string($ce_title), 1, $ce_title);
	Newt::PushHelpLine($ce_help);
	$ce_panel = Newt::Panel(3, 20, "CDDB Search");
	$ce_panel->Add(0, 0, $wait_label);

	($reason, $data) = $ce_panel->Draw();
	Newt::Refresh();

	# CDDB query
	my %ce_cd = get_cddb(\%ce_config);

	# Modify enconding of some fields
	$ce_cd{artist} = decode("iso8859-1",$ce_cd{artist});
	$ce_cd{title} = decode("iso8859-1",$ce_cd{artist});

	# Third panel to display CD Infos
	Newt::DrawRootText(ce_center_string($ce_title), 1, $ce_title);
	Newt::PushHelpLine($ce_help);

	# Components
	$flag = NEWT_ENTRY_SCROLL;
	$width = 40;
	my $artist_entry = Newt::Entry($width, $flag, $ce_cd{artist});
	my $title_entry = Newt::Entry($width, $flag, $ce_cd{title});
	my $category_entry = Newt::Entry($width, $flag, $ce_cd{cat});
	my $genre_entry = Newt::Entry($width, $flag, $ce_cd{genre});
	my $data_entry = Newt::Entry($width, $flag, Dumper(@{$ce_cd{data}}));
	my $raw_entry = Newt::Entry($width, $flag, Dumper(@{$ce_cd{raw}}));
	my $tno_entry = Newt::Label($ce_cd{tno});
	$width = 5;
	my $year_entry = Newt::Entry($width, $flag, $ce_cd{year});
	
	# Build interface
	$ce_panel = Newt::Panel(3, $ce_sh, "CDDB Info");
	$ce_panel->Add(0, 0, $artist_label);
	$ce_panel->Add(1, 0, $artist_entry, $flage);
	$ce_panel->Add(0, 1, $title_label);
	$ce_panel->Add(1, 1, $title_entry, $flage);
	$ce_panel->Add(0, 2, $year_label);
	$ce_panel->Add(1, 2, $year_entry, $flage);
	$ce_panel->Add(0, 3, $category_label);
	$ce_panel->Add(1, 3, $category_entry, $flage);
	$ce_panel->Add(0, 4, $genre_label);
	$ce_panel->Add(1, 4, $genre_entry, $flage);
	$ce_panel->Add(0, 5, $data_label);
	$ce_panel->Add(1, 5, $data_entry, $flage);
	$ce_panel->Add(0, 6, $raw_label);
	$ce_panel->Add(1, 6, $raw_entry, $flage);
	$ce_panel->Add(0, 7, $tno_label);
	$ce_panel->Add(1, 7, $tno_entry, $flage);
	#$ce_panel->Add(0, 5, $info_label);
	#$ce_panel->Add(1, 5, $info_entry, $flage);

	my $n=1;
	$width = 40;
  	while ( $n <= $ce_cd{tno} ) {
		last if ($n > $ce_sh - 8);
		my $from=$ce_cd{frames}[$n-1];
		my $to=$ce_cd{frames}[$n]-1;
		my $dur=$to-$from;
		my $min=int($dur/75/60);
		my $sec=int($dur/75)-$min*60;
		my $frm=($dur-$sec*75-$min*75*60)*100/75;
		my $tr = sprintf "Track %2d:", $n;
		my $track_label = Newt::Label($tr);
		$tr = sprintf " %2d':%.2d", $min, $sec;
		my $dur_label = Newt::Label($tr);
		$flag = NEWT_FLAG_WRAP|NEWT_ENTRY_SCROLL;
		# Adapt encoding of track
		$ce_cd{track}[$n -1] = decode("iso8859-1",$ce_cd{track}[$n -1]);
		my $track_entry = Newt::Entry($width, $flag, $ce_cd{track}[$n-1]);
		$ce_panel->Add(0, 8+$n, $track_label);
		$ce_panel->Add(1, 8+$n, $track_entry, $flage);
		$ce_panel->Add(2, 8+$n, $dur_label, $flage);
		$n++;
  	}

	$ce_panel->Add(0, 8+$n, $send_button);
	$ce_panel->Add(1, 8+$n, $reload_button);
	$ce_panel->Add(2, 8+$n, $quit_button);
	
	Newt::Cls();
	Newt::Refresh();
	# Build interface
	($reason, $data) = $ce_panel->Run();

	$ce_cd{artist} = $artist_entry->Get();
	$ce_cd{title} = $title_entry->Get();
	$ce_cd{year} = $year_entry->Get();
	$ce_cd{cat} = $category_entry->Get();
	$ce_cd{genre} = $genre_entry->Get();
	Newt::Refresh();
	Newt::Cls();
	exit 0 if ($data->Tag() eq "Quit");

	# Send the data
	if ($data->Tag() eq "Send") {
		$flag = NEWT_FLAG_WRAP;
		$width = 40;
		my $height = 25;
		my $info_tb = Newt::Textbox($width, $height, $flag, Dumper(keys %ce_cd));

		Newt::DrawRootText(ce_center_string($ce_title), 1, $ce_title);
		Newt::PushHelpLine($ce_help);

		Newt::Cls();
		$ce_panel = Newt::Panel(3, $width, "CDDB Sending Infos");
		$ce_panel->Add(0, 0, $wait_label);
		$ce_panel->Add(0, 1, $info_tb);
		$ce_panel->Add(0, 2, $quit_button);
		Newt::Refresh();
		($reason, $data) = $ce_panel->Run();
	}
}
Newt::Finished();
exit 0;

# return the char to start printing a centered string based on screen size
sub ce_center_string {

	my $string = shift || "";

	my $res = ($ce_sl / 2 ) - (length($string) / 2);
	if ($res < 0 ) {
		return 0;
	} else {
		return ($res);
	}
}

1;
