#
# tesouro.pm
#

# Version 0.1 - Obtêm o preço de venda dos Títulos Públicos.
# Retirado de http://www.bmfbovespa.com.br/pt-br/mercados/outros-titulos/tesouro-direto/tesouro-direto.aspx
# Usar código da forma:
# LTN010121013  : Letras do Tesouro Nacional vencimento em 01/01/2013
# NTNBP15052015 : NTN-B Principal com vencimento em 15/05/2015
# LFT07032017   : LFT com vencimento em 07/03/2017
# NTNF01012021  : NTN-F com vencimento em 01/01/2021
#
# Este módulo foi baseado no módulo ZA.pm
# Rafael Casali
# 03-01-2012

package Finance::Quote::tesouro;
require 5.004;

use strict;
use vars qw /$VERSION/ ;

use LWP::UserAgent;
use HTTP::Request::Common;
use HTML::TableExtract;
use HTML::Tree;
use Data::Dumper;
use Date::Manip::Date;

$VERSION = '1.17';

my $BMFBOVESPA_MAINURL = ("http://www.bmfbovespa.com.br/");
my $BMFBOVESPA_URL = ($BMFBOVESPA_MAINURL."pt-br/mercados/outros-titulos/tesouro-direto/tesouro-direto.aspx");

sub methods {
    return (tesouro => \&bmfbovespa);
}


sub labels {
    my @labels = qw/method source name symbol currency last date /;
    return (bmfbovespa => \@labels);
}   

sub convert_price {
        $_ = shift;
        s/\.//g;
        s/,/\./g;
        return $_;
}

sub clean_title {
	$_ = shift;
	s/-//g;
	s/ //g;
	s/rincipal//g;
	return $_;
}


sub bmfbovespa {

    my $quoter = shift;
    my @symbols = @_;
    my %info;
    my ($te, $ts, $row);
    my @rows;
    my $name;

    return unless @symbols;

    my $ua = $quoter->user_agent;

    foreach my $symbol (@symbols) {
        my $url = $BMFBOVESPA_URL;
#        print "[debug]: ", $url, "\n";
        my $response = $ua->request(GET $url);
#        print "[debug]: ", $response->content, "\n";

        if (!$response->is_success) {
            $info{$symbol, "success"} = 0;
            $info{$symbol, "errormsg"} = "Error contacting URL";
            next;
        }

	$te = new HTML::TreeBuilder;
	$te->parse($response->content); 

	my $posicao=$te->look_down('class','obs');

	 
	my $dia = substr $posicao->as_text(), -10;
	$te->delete;
        $te = new HTML::TableExtract();
        $te->parse($response->content);

	
#        print "[debug]: (parsed HTML)",$te, "\n";

#	unless ($te->first_table_found()) {
#	  print STDERR  "no tables on this page\n";
	  $info{$symbol, "success"}  = 0;
	  $info{$symbol, "errormsg"} = "Parse error";
#	  next;
#	}

# Debug to dump all tables in HTML...
#	print "[debug]: $symbol \n";

 #          print "\n \n \n \n[debug]: ++++ ==== ++++ ==== ++++ ==== ++++ ==== START OF TABLE DUMP ++++ ==== ++++ ==== ++++ ==== ++++ ==== \n \n \n \n";
#
         foreach $ts ($te->table_states) {;
#
#           printf "\n \n \n \n[debug]: //// \\\\ //// \\\\ //// \\\\ //// \\\\ START OF TABLE %d,%d //// \\\\ //// \\\\ //// \\\\ //// \\\\ \n \n \n \n",
#	     $ts->depth, $ts->count;
#
           foreach $row ($ts->rows) {
		next unless $row->[0];
		my $venc = new Date::Manip::Date;
		$venc->config('DateFormat','non-US');
		$venc->parse_date($row->[1]);
		my $titulo = clean_title($row->[0]) . $venc->printf('%d%m%Y');
		if($titulo eq $symbol){ 		
	  	$quoter->store_date(\%info, $symbol, {eurodate => $dia });
          	$info{$symbol, "last"}  = convert_price(clean_title($row->[6]));
          	$info{$symbol, "name"} = $row->[0] ." " . $row->[1];
		$info{$symbol, "success"} = 1;
        	$info{$symbol, "method"} = "BMFBOVESPA";
#
        	$info{$symbol, "symbol"} = $symbol;
        	$info{$symbol, "currency"} = "BRL";
        	$info{$symbol, "source"} = $BMFBOVESPA_MAINURL;
#		print Dumper($row);
		}
           }
         }

#
#           print "\n \n \n \n[debug]: ++++ ==== ++++ ==== ++++ ==== ++++ ==== END OF TABLE DUMP ++++ ==== ++++ ==== ++++ ==== ++++ ==== \n \n \n \n";


# GENERAL FIELDS

    }

    return wantarray() ? %info : \%info;
}

1;

=head1 NAME

Finance::Quote::Tesouro - Obtain brazilian papers from
www.bmvbovespa.com.br

=head1 SYNOPSIS

    use Finance::Quote;

    $q = Finance::Quote->new;

    # Don't know anything about failover yet...

=head1 DESCRIPTION

This module obtains information about brazilian debentures from
www.bmvbovespa.com.br

=head1 LABELS RETURNED

Information available from sharenet may include the following labels:

method source name symbol currency date nav last price

=head1 SEE ALSO

BMFBovespa website - http://www.bmvbovespa.com.br

Finance::Quote

=cut

