#!/usr/bin/perl
use strict;

use LWP::Simple;
use XML::LibXML;

#note: LibXML will fail if just xmlns= and not xmlns:gml=    - need fully qualified

my ($org,$url);

#my @array_org = qw(gcoos secoora macoora neracoos glos pacioos aoos nanoos cencoos sccoos ndbc coop ace);
my @array_org = qw(ndbc);

while (@array_org) {

$org = shift (@array_org);

#Eastern
#GCOOS
if ($org eq 'gcoos') {
  $url = 'http://gcoos.rsmas.miami.edu/sos/sos_server.php?request=GetCapabilities&service=SOS';
}
#SECOORA
if ($org eq 'secoora') {
  $url = 'http://neptune.baruch.sc.edu/cgi-bin/oostethys_sos.cgi?request=GetCapabilities&service=SOS';
}
#MACOORA_WF
if ($org eq 'macoora') {
  $url = 'http://www.weatherflow.com/sos/sos.pl?request=GetCapabilities&service=SOS';
}
#NERACOOS
if ($org eq 'neracoos') {
  $url = 'http://www.neracoos.org/cgi-bin/sos/V1.0/oostethys_sos.cgi?request=GetCapabilities&service=SOS'; 
}
#GLOS
if ($org eq 'glos') {
  $url = 'http://michigan.glin.net/glos/sos/sos.php?request=GetCapabilities&service=SOS'; 
}

#Western
#PACIOOS
if ($org eq 'pacioos') {
  $url = 'http://oos.soest.hawaii.edu/oostethys/sos?request=GetCapabilities&service=SOS';
}
#AOOS
if ($org eq 'aoos') {
  $url = 'http://svc.axiomalaska.com:8080/sos2/sos?request=GetCapabilities&service=SOS'; #numerous system type id's
  #$url = 'http://ak.aoos.org/ows/sos.php?request=GetCapabilities&service=SOS'; #timed out
}
#NANOOS
if ($org eq 'nanoos') {
  $url = 'http://data.stccmop.org/ws/util/sos.py?request=GetCapabilities&service=SOS';
}
#CENCOOS
if ($org eq 'cencoos') {
  $url = 'http://204.115.180.244/sos/server.php?request=GetCapabilities&service=SOS'; 
}
#SCCOOS
if ($org eq 'sccoos') {
  $url = 'http://sccoos-obs0.ucsd.edu/sos/server.php?request=GetCapabilities&service=SOS'; 
}

#Federal
#NDBC
if ($org eq 'ndbc') {
  $url = 'http://sdf.ndbc.noaa.gov/sos/server.php?request=GetCapabilities&service=SOS';
}
#CO-OP
if ($org eq 'coop') {
  $url = 'http://opendap.co-ops.nos.noaa.gov/ioos-dif-sos/SOS?request=GetCapabilities&service=SOS';
}
#ACE
if ($org eq 'ace') {
  $url = 'http://sos.usace.army.mil/oracle_server.php?request=GetCapabilities&service=SOS';
}

#store documents initially and rename with $org suffix and manually fix documents for now  
getstore($url,'./latest.txt') or die "Couldn't get $url\n";

##########################################
#differences between sos's
my $sos_ns_prefix = 'sos:';

if ($org eq 'gcoos' || $org eq 'macoora' || $org eq 'coop') {
  $sos_ns_prefix = '';
}

#####
my $vocab_delimiter = '#';

if ($org eq 'gcoos' || $org eq 'cencoos' || $org eq 'pacioos' || $org eq 'coop' || $org eq 'ace' || $org eq 'ndbc') {
  $vocab_delimiter = '/';
}
if ($org eq 'neracoos' || $org eq 'aoos') {
  $vocab_delimiter = ':';
}

#####
#uri vocab prefixes

#pacioos,cencoos,ndbc,coop,ace
#http://mmisw.org/ont/cf/parameter/

#gcoos
#http://mmisw.org/ont/gcoos/parameter/

#nanoos,sccoos,macoora,glos
#http://www.csc.noaa.gov/ioos/schema/IOOS-DIF/IOOS/0.6.1/dictionaries/phenomenaDictionary.xml#

#neracoos
#urn:ogc:def:phenomenon:mmisw.org:cf:

#aoos
#urn:ogc:def:phenomenon:OGC:1.0.30:SwellPeriod

#secoora
#http://carolinasrcoos.org/cf#

##########################################


#normally kml tag would include xmlns like following, but xmlns has processing problem issues with XML::LibXML - <kml xmlns="http://earth.google.com/kml/2.1">
my $xml_content = <<"END_OF_FILE";
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns:kml="http://earth.google.com/kml/2.1" xmlns:obsList="http://carocoops.org/obskml/1.0.0/obskml_simple.xsd">
<!-- JTC - please forgive any unorthodoxy in the namespace declaration above, there's a bug with the perl XML::XPath package I'm using where all xmlns must be declared in the root element using prefix notation -->
<Document>
<name>SOS platforms/obs by $org</name>
<open>1</open>
END_OF_FILE

my $xp = XML::LibXML->new->parse_file("./out/latest.txt.$org");

#my $xp_xml = $xp->serialize; #debug
#print $xp_xml;


open(FILE,">out/out_$org");

#      <ObservationOffering gml:id="station-42003">

print FILE "org:$org\n\n";
my $platform_count = 0;

my %hash_terms = ();

foreach my $platform ($xp->findnodes("//".$sos_ns_prefix."ObservationOffering")) {
	$platform_count++;

        my $platform_id = sprintf("%s",$platform->getAttribute('gml:id'));

        my $platform_lc = sprintf("%s",$platform->find('gml:boundedBy/gml:Envelope/gml:lowerCorner')); 
        my $platform_uc = sprintf("%s",$platform->find('gml:boundedBy/gml:Envelope/gml:upperCorner')); 
        my $location = '';
	if ($platform_lc eq $platform_uc) { $location = $platform_uc; } else { $location = 'box:'.$platform_lc.':'.$platform_uc; }
        print FILE "platform:$platform_id:$location\n";
        
=comment
        <gml:boundedBy>
          <gml:Envelope srsName="urn:ogc:def:crs:epsg::4326">
            <gml:lowerCorner>16.834 -97.61045</gml:lowerCorner>
            <gml:upperCorner>31.418 -80.097</gml:upperCorner>
          </gml:Envelope>
        </gml:boundedBy>
=cut
# <sos:observedProperty xlink:href="http://carolinasrcoos.org/cf#water_temperature"/>

	my $term_list = '';
	foreach my $obs ($platform->findnodes($sos_ns_prefix."observedProperty")) {
		my $uri = sprintf("%s", $obs->getAttribute('xlink:href'));
		my (@array_vocab_term) = split(/$vocab_delimiter/,$uri);
                my $term = @array_vocab_term[-1]; 
		$term_list .= "$term,";
		$hash_terms{$uri}++;
	}
	chop($term_list);
	print FILE "obs_list:$term_list\n";


	my ($lat,$lon) = split(/\s+/,$location);
	$xml_content .= <<"END_OF_FILE";
	<Placemark>
	<name>$platform_id</name>
	<description>$term_list</description>
          <Point>
          <coordinates>$lon,$lat</coordinates>
          </Point>
        </Placemark>
END_OF_FILE

#print "td:".$td->to_literal()."\n";

} #foreach $platform

print FILE "\nplatform_count:$platform_count\n";

print FILE "\nsos_url $url\n"; 
print FILE "terms_list:\n";

my @sorted = sort { $hash_terms{$a} <=> $hash_terms{$b} } keys %hash_terms;
#foreach my $term (keys %hash_terms) {
foreach my $term (@sorted) {
  print FILE "term:$term:$hash_terms{$term}\n";
}

close(FILE);

$xml_content .= "</Document>\n</kml>";

open(FILE_KML,">./out/$org.kml");
print FILE_KML $xml_content;
close(FILE_KML);

`zip out/$org.kmz out/$org.kml`;

} #while $org

exit 0;
