#
# tesouro.pm
#http://www3.tesouro.gov.br/tesouro_direto/consulta_titulos_novosite/consultatitulos.asp
#
# Version 0.5
# Change URL
# "https://www.tesourodireto.com.br/titulos/precos-e-taxas.htm"
# 2020.07.05
#
# Version 0.4
# Change URL
# 2017.11.05
#
# Version 0.3
# Change URL and codes
# 2016.10.21

# Version 0.2
# Change URL and codes
# 2016.03.12

# Version 0.1
# Update to new layout of site
# 2015.12.18


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

use strict;
use vars qw /$VERSION $DEBUG/ ;

use LWP::UserAgent;
use JSON;
use Data::Dumper;

#$VERSION = '1.49';

our $DEBUG = 0;

my $TESOURO_MAINURL = ("http://www.tesouro.gov.br/");
#my $TESOURO_URL = ("http://www.tesourodireto.com.br/titulos/precos-e-taxas.htm");
my $TESOURO_URL = ("https://www.tesourodireto.com.br//json/br/com/b3/tesourodireto/service/api/treasurybondsinfo.json");

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/R//g;
	s/\$//g;
        s/\.//g;
        s/,/\./g;
        return $_;
}

sub convert_date {
	$_ = shift;
	s/-/\//g;
	return $_;
}

sub changedate {
  join '', reverse split /\b/, shift;
}

sub clean_title {
	$_ = shift;
	s/-//g;
	s/[0-9]*//g;
	s/ //g;
	s/\t//g;
	s/Tesouro//g;
	s/rincipal//g;
	s/\(.*\)//;
#	s/\)//;
	s/\n//g;
	s/\r//g;
	return $_;
}


sub bmfbovespa {

    my $quoter = shift;
    my @symbols = @_;
    my %info;

    return unless @symbols;

    my $ua = $quoter->user_agent;
    $ua->ssl_opts(
    SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE, 
    verify_hostname => 0);
    my $url = $TESOURO_URL;
    if ($DEBUG) {
        print "[debug]: ", $url , "\n";
    }

    my $response = $ua->get($url);
    my $code =  $response->code;

    if ($DEBUG) {
	    #	print "[debug]: ", $response->as_string, "\n";
	print "[debug]: ", $response->code, "\n";
    }

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

   if ( $code == 200 ) {

    # Buscando a Data da cotação.
    my $data = JSON::decode_json $response->content;
    
    my $json_resources = $data->{'response'};

    my ($dia,$hora) = split(/T/,$json_resources->{'TrsrBondMkt'}{'qtnDtTm'});

    $dia= changedate(convert_date($dia));

    foreach my $symbol (@symbols) {
	
	$info{$symbol, "success"}  = 0;
	$info{$symbol, "last"} = "";
	$info{$symbol, "errormsg"} = "Symbol $symbol is not found";

	my $titulos = $json_resources->{'TrsrBdTradgList'};
  	for my $busca ( @{$json_resources->{'TrsrBdTradgList'}} ) {
		my $vencimento = $busca->{'TrsrBd'}{'mtrtyDt'};
		$vencimento =~ m/T/;
		$vencimento =changedate(convert_date($`));
		my $venc = $vencimento;
		$vencimento =~ s/\///g;
	
		my $nome= $busca->{'TrsrBd'}{'nm'};
		my $titulo = clean_title($nome ) . $vencimento;
		if($titulo eq $symbol){  
  	  		$quoter->store_date(\%info, $symbol,{ eurodate => $dia});
		  	$info{$symbol, "last"}  = $busca->{'TrsrBd'}{'untrRedVal'};
		  	$info{$symbol, "name"} = $busca->{'TrsrBd'}{'nm'} . $venc ;
	  		$info{$symbol, "price"} = $info{$symbol, "last"};
		  	$info{$symbol, "success"} = 1;
		  	$info{$symbol, "method"} = "tesouro";
	  		$info{$symbol, "symbol"} = $symbol;
		  	$info{$symbol, "currency"} = "BRL";
		  	$info{$symbol, "source"} = $TESOURO_MAINURL;
			last;
		}
	  
	}

    }

}

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

1;

=head1 NAME

Finance::Quote::Tesouro - Obtain brazilian papers from
www.tesouro.fazenda.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.tesouro.fazenda.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

Finance::Quote

=cut

