###########################################################################
#
# WgetDownload.pm -- Download base module that handles calling Wget
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 2006 New Zealand Digital Library Project
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
###########################################################################

package WgetDownload;

eval {require bytes};

# suppress the annoying "subroutine redefined" warning that various
# plugins cause under perl 5.6
$SIG{__WARN__} = sub {warn($_[0]) unless ($_[0] =~ /Subroutine\s+\S+\sredefined/)};

use BasDownload;
use strict;
use IPC::Open2;

sub BEGIN {
    @WgetDownload::ISA = ('BasDownload');
}

my $arguments = 
     [ { 'name' => "proxy_on", 
	'desc' => "{WgetDownload.proxy_on}",
	'type' => "flag",
	'reqd' => "no",
	'hiddengli' => "yes"},
      { 'name' => "proxy_host",  
	'desc' => "{WgetDownload.proxy_host}",         
	'type' => "string",
	'reqd' => "no",
	'hiddengli' => "yes"},
      { 'name' => "proxy_port", 
	'desc' => "{WgetDownload.proxy_port}",         
	'type' => "string",
	'reqd' => "no",
	'hiddengli' => "yes"},
      { 'name' => "user_name",  
	'desc' => "{WgetDownload.user_name}",         
	'type' => "string",
	'reqd' => "no",
	'hiddengli' => "yes"},
      { 'name' => "user_password", 
	'desc' => "{WgetDownload.user_password}",         
	'type' => "string",
	'reqd' => "no",
	'hiddengli' => "yes"}];

my $options = { 'name'     => "WgetDownload",
		'desc'     => "{WgetDownload.desc}",
		'abstract' => "yes",
		'inherits' => "yes",
		'args'     => $arguments };


sub new {
    my ($class) = shift (@_);
    my ($getlist,$inputargs,$hashArgOptLists) = @_;
    push(@$getlist, $class);

    if(defined $arguments){ push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});}
    if(defined $options) { push(@{$hashArgOptLists->{"OptList"}},$options)};

    my $self = (defined $hashArgOptLists)? new BasDownload($getlist,$inputargs,$hashArgOptLists): new BasDownload($getlist,$inputargs);

    return bless $self, $class;
}

sub checkWgetSetup
{
    my ($self,$blnGliCall) = @_;
    #TODO: proxy detection??
    
    if((!$blnGliCall) && $self->{'proxy_on'})
    {
	&checkProxySetup($self);
    }
    &checkURL($self); 
}

sub getWgetOptions
{
    my ($self) = @_;
    my $strOptions = "";
    
    if($self->{'proxy_on'} && $self->{'proxy_host'} && $self->{'proxy_port'} 
       && $self->{'user_name'} && $self->{'user_password'} 
       )
    {
	$strOptions = " -e httpproxy=$self->{'proxy_host'}:$self->{'proxy_port'} --proxy-user=$self->{'user_name'}"." --proxy-passwd=$self->{'user_password'} -Y on ";
    }

    return $strOptions;
}

# Checking for proxy setup: proxy server, proxy port, proxy username and password.
sub checkProxySetup
{
    my ($self) = @_;
    ($self->{'proxy_on'}) || &error("checkProxySetup","The proxy is not on? How could that be happening?");
    # Setup .wgetrc by using $self->{'proxy_host'} and $self->{'proxy_port'}
    # Test if the connection is succeful. If the connection wasn't succeful then ask user to supply username and password.

}

sub useWget
{
    my ($self, $cmdWget,$blnShow) = @_;

    my ($os,$strReadIn,$strLine,$command);
   
    $os = $ENV{'GSDLOS'};
 
  
    if ($os =~ /windows/i){
	$command = "\"$ENV{'GSDLHOME'}\\bin\\windows\\wget\" $cmdWget |";
    }
    else{
        $command = "$ENV{'GSDLHOME'}/packages/wget/wget-1.9/src/wget $cmdWget |";  
    }

    

   open(*WIN,$command) || die "wget request failed: $!\n";

    

    while (defined($strLine=<WIN>))
    {


	if($blnShow)
	{
	    print STDERR "$strReadIn\n";
	}

	$strReadIn .= $strLine;
    }

    close(WIN);

    return $strReadIn;
}

# TODO: Check if the URL is valid?? Not sure what should be in this function yet!!
sub checkURL
{
    my ($self) = @_;
    if ($self->{'url'} eq "")
    {
	&error("checkURL","no URL is specified!! Please specifies the URL for downloading.");
    }
}

sub error
{
    my ($strFunctionName,$strError) = @_;
    {
	print "Error occoured in WgetDownload.pm\n".
	    "In Function:".$strFunctionName."\n".
	    "Error Message:".$strError."\n";
	exit(-1);
    }
}

1;
