package Finance::Quote::FSMHK;
require 5.004;

use strict;

use vars qw($VERSION $FSMHK_URL);

use LWP::UserAgent;
use HTTP::Request::Common;

$VERSION = '1.18';
$FSMHK_URL = 'http://www.fundsupermart.com.hk/hk/main/fundinfo/viewFund.svdo?lang=en&sedolnumber=';

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

{
  my @labels = qw/date year month day method source name currency price/;

  sub labels { return (fsmhk => \@labels); }
}

sub fsmhk {
  my $quoter  = shift;
  my @symbols = @_;

  return unless @symbols;
  my ($ua, $reply, $url, %funds, $name);
  my (@decoded_html, $decoded_html, $currency_price_date, $currency, $price);

  foreach my $symbol (@symbols) {
    $name = $symbol;
    $url = $FSMHK_URL;
    $url = $url . $name;
    $ua    = $quoter->user_agent;
    $reply = $ua->request(GET $url);
    unless ($reply->is_success) {
	  foreach my $symbol (@symbols) {
        $funds{$symbol, "success"}  = 0;
        $funds{$symbol, "errormsg"} = "HTTP failure";
	  }
	  return wantarray ? %funds : \%funds;
    }

    my @decoded_html = split(/\n+/,$reply->content);
    my $decoded_html;

    while ($decoded_html = shift @decoded_html){
	    ($decoded_html =~ /Latest NAV Price/) && last;
    }

    $currency_price_date = shift @decoded_html;
    # like this: <td class=table_bdtext_style>USD 37.9<br>(as of April 24, 2013)
    $currency_price_date =~ s/\<.*?\>/ /g;
    $currency_price_date =~ s/^\s*//;
    ($currency, $price) = split(/ /, $currency_price_date);

    $funds{$name, 'method'}   = 'fsmhk';
    $funds{$name, 'price'}    = $price;
    $funds{$name, 'currency'} = $currency;
    $funds{$name, 'success'}  = 1;
    $funds{$name, 'symbol'}  = $name;
    $funds{$name, 'source'}   = 'Finance::Quote::FSMHK';
    $funds{$name, 'name'}   = $name;
    $funds{$name, 'p_change'} = "";  # p_change is not retrieved (yet?)

    $currency_price_date =~ /\(.*([A-Z]\w+) +(\d\d?)\, +(\d\d\d\d)\)/;
    $quoter->store_date(\%funds, $name, {year => $3, month => $1, day => $2});
    

    # Check for undefined symbols
    foreach my $symbol (@symbols) {
	  unless ($funds{$symbol, 'success'}) {
        $funds{$symbol, "success"}  = 0;
        $funds{$symbol, "errormsg"} = "Fund name not found";
	  }
    }
  }
  return %funds if wantarray;
  return \%funds;
}

1;


=head1 NAME

Finance::Quote::FSMHK - Obtain fund prices from Fundsupermart HK

=head1 SYNOPSIS

    use Finance::Quote;

    $q = Finance::Quote->new;

    %fundinfo = $q->fetch("fsmhk","Sedol number");

=head1 DESCRIPTION

This module obtains information about FSM fund prices from
http://www.fundsupermart.com.hk/hk/main/fundinfo/viewFund.svdo?lang=en&sedolnumber=xxx

=head1 SEDOL NUMBER

You can get the Sedol Number from the end of URL of the fund in FSM page.

=head1 LABELS RETURNED

Information available may include the following labels:
date method source name currency price

=head1 SEE ALSO

http://en.wikipedia.org/wiki/SEDOL

=cut