#!/usr/bin/perl

use strict;
use warnings;
use vars qw(%opts %orgs);
use Data::Dumper;

use Getopt::Std;

# SOAP:Lite må modifiseres til å gjøre ting på MS måten :-/
use SOAP::Lite on_action => sub {sprintf '%s/%s', @_}, ;

sub get_tono_stats {
    my $soap = new SOAP::Lite
        -> uri('http://localhost/CommunitySiteService')
        -> proxy('http://communitysite1.frikanalen.tv/CommunitySiteFacade/CommunitySiteService.asmx');

    my $obj = $soap->SearchVideos(
        SOAP::Data->name('searcher' => {
            'PredefinedSearchType' => 'Default',
            'Take' => 10000,
                         }
        )
        );
    if ($obj->fault) {
        print join ', ',
              $obj->faultcode,
              $obj->faultstring;
        return;
    }

    my $res = $obj->result;
#    print Dumper($res);
    unless ($res->{'Data'}) {
        return;
    }
    my $tono = 0;
    my $notono = 0;
    foreach my $video (@{$res->{'Data'}->{'Video'}}) {
        if ("true" eq $video->{'HasTonoRecords'}) {
            $tono++;
            $orgs{$video->{'Organization'}}{tono}++;
            push(@{$orgs{$video->{'Organization'}}{tonoids}},
                 $video->{MetaDataVideoId});
#            print Dumper($video);
#            exit 0;
        } else {
            $notono++;
            $orgs{$video->{'Organization'} || ""}{notono}++;
        }
    }
    return ($tono, $notono);
}
sub print_tono_stats {
    my ($with, $without) = get_tono_stats();
    printf("Innslag med tono-musikk:   %d (%.1f%%)\n",   $with, 100 * $with / ($with+$without));
    printf("Innslag uten tono-musikk:  %d (%.1f%%)\n",$without, 100 *$without/($with+$without));

    print "Andel\tmed\tuten\tnavn\n";
    for my $org (sort tonoorder keys %orgs) {
        my $tono = $orgs{$org}{tono} || 0;
        my $notono = $orgs{$org}{notono} || 0;
        my $frac = 100 * $tono / $with;
        printf "%4.1f\t%d\t%d\t%s\n", $frac, $tono, $notono, $org;
        print join(" ", "  ", @{$orgs{$org}{tonoids}}), "\n"
            if $opts{'i'} && exists $orgs{$org}{tonoids};
    }
}

sub tonoorder {
   my $order = ($orgs{$b}{tono} || 0) <=> ($orgs{$a}{tono} || 0);
   if (0 == $order) {
      $order = ($orgs{$b}{notono} || 0) <=> ($orgs{$a}{notono} || 0);
   }
   return $order;
}

sub munin_plugin {
    my @ARGV = @_;
    if (defined $ARGV[0] && "config" eq $ARGV[0]) {
        print <<EOF;
graph_title Fraction of events with Tono-related music
graph_category Frikanalen
tono_frac.label fraction
EOF
    } else {
        my ($with, $without) = get_tono_stats();
        printf "tono_frac.value %.3f\n", ($with / ($with + $without));
    }
}

getopts("im", \%opts);

if ($opts{'m'}) {
    munin_plugin(@ARGV);
} else {
    print_tono_stats();
}
