#!/usr/bin/perl
#
#	Copyright 2016 (c) Shin-ichi Nagamura.
#	All rights reserved.
#
#	$Id: getAmedas 93 2016-09-24 19:44:53Z core $
#


use	utf8 ;
use	strict ;
use	warnings ;

use	kuon ;
use	kuon::Amedas ;

use	Getopt::Long ;

binmode	STDOUT,	":utf8" ;
binmode	STDERR,	":utf8" ;


# ----- options -----
my	$opt_help				= 0 ;
my	$opt_fetch2				= 0 ;

my	%options	= (
		"debug"				=> \$kuon::opt_dbg,
		"fetch2"			=> \$opt_fetch2,
		"verbose"			=> \$kuon::opt_msg,
		"help"				=> \$opt_help,
	) ;


sub		usage( $ )
{
	my	$rc	= shift ;

	printf( "usage: getAmedas [OPTIONS...] LOCATIONCODE\n" ) ;
	printf( "--debug     for debugging\n" ) ;
	printf( "--fetch2    use fetch2()\n" ) ;
	printf( "--verbose   verbose mode\n" ) ;
	printf( "--help      show this message\n" ) ;
	exit( $rc ) ;
}


sub		dmpdata1( $ )
{
	my	$ret	= shift ;

	my	@hdrs	= @{$ret->{hdrs}} ;
	my	@data		= @{$ret->{data}} ;

	foreach my $data ( @data ) {
		printf( "%s", scalar localtime( $data->{dt} )) ;
		foreach my $hdr ( @hdrs ) {
			printf( ",%s", $data->{$hdr} ) ;
		}
		printf( "\n" ) ;
	}
}


sub		dmpdata2( $ )
{
	my	$ret	= shift ;

	die( "not found data2" )		unless( $ret->{data2} ) ;
	my	@hdrs	= @{$ret->{hdrs}} ;
	my	%data2	= %{$ret->{data2}} ;

	foreach my $dt ( sort( keys( %data2 ))) {
		my	$data	= $data2{$dt} ;
		printf( "%s", scalar localtime( $dt )) ;
		foreach my $hdr ( @hdrs ) {
			printf( ",%s", $data->{$hdr} ) ;
		}
		printf( "\n" ) ;
	}
}


sub		main( @ )
{
	# ----- read options -----
	Getopt::Long::Configure( "bundling" ) ;
	&usage( 1 )		unless( GetOptions( %options )) ;
	&usage( 0 )		if( $opt_help ) ;
	&usage( 1 )		if( $#ARGV < 0 ) ;

	my	$locationcode	= shift( @ARGV ) ;

	my	$ret		= ( $opt_fetch2 ) ? kuon::Amedas::fetch2( $locationcode )
									  : kuon::Amedas::fetch( $locationcode ) ;
	die( "could not fetch" )			unless( $ret ) ;
	my	@hdrs		= @{$ret->{hdrs}} ;
	my	%units		= %{$ret->{units}} ;
	my	@data		= @{$ret->{data}} ;
	die( "fatal error" )				unless( @hdrs && %units && @data ) ;

	printf( "%s\n", $ret->{name} ) ;

	my	$comma	= "" ;
	foreach my $hdr ( @hdrs ) {
		printf( "%s%s", $comma, $hdr ) ;
		$comma	= "," ;
	}
	printf( "\n" ) ;

	$comma	= "" ;
	foreach my $hdr ( @hdrs ) {
		printf( "%s%s", $comma, $units{$hdr} ) ;
		$comma	= "," ;
	}
	printf( "\n" ) ;

	if( $opt_fetch2 ) {
		dmpdata2( $ret ) ;
	} else {
		dmpdata1( $ret ) ;
	}

	return( 0 ) ;
}


exit( main()) ;
