#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;

use Data::Dump 'pp';
use Text::CSV;

my %BROWSERID = qw(
	IE          trident
	Firefox     gecko
	Safari      webkit_saf
	Safari-iPad ios_saf
	Chrome      webkit_chr
	Opera       presto
);

my %count = (
	-source => 'StatCounter',
	-site   => 'http://gs.statcounter.com/',
);
my $input = \*STDIN;

if (@ARGV) {
	my %param = (
		bar             => 1,
		statType_hidden => 'browser_version',
		region_hidden   => 'ww', # NL
		granularity     => 'monthly',
		statType        => 'Browser%20Version',
		region          => 'Worldwide', # Netherlands
		fromMonthYear   => $ARGV[0],
		toMonthYear     => $ARGV[1] // $ARGV[0],
		csv             => 1,
	);
	my $url = $count{-site};
	$url .= 'chart.php?'.join('&', map "$_=$param{$_}", keys %param);
	$count{-url} = $url;
	require LWP::Simple;
	my $download = LWP::Simple::get($url) or die "No data from $url\n";
	undef $input;
	open $input, '<', \$download or die $!;
}

my $csv = Text::CSV->new or die Text::CSV->error_diag;
while (my $row = $csv->getline($input)) {
	my ($browser, $pct) = @$row;
	$browser and $pct or next;

	my $version = $browser =~ s/ (\d\S*)$// ? $1 : 0;
	given ($browser) {
		when ('Browser Version') {
			$pct =~ s/^Market Share % // and $count{-date} = $pct;
		}
		$browser =~ tr/ /-/;
		$browser = $_ for $BROWSERID{$browser} // ();
		$version =~ s/\.0$//;
		$count{$browser}->{$version} += $pct;
	}
}
$csv->eof or $csv->error_diag;

print pp(\%count);

__END__

=head1 USAGE

cat <csv data> | F<convert-stats-gs> > browser-usage-gs.inc.pl

F<convert-stats-gs> <year-month>

