#!/usr/bin/perl
#

use SOAP::Lite  on_action => sub {sprintf '%s/%s', @_}, ;

use Data::Dumper;
my $frikanal_meta_subset;
my $localvideo_dir = '/data/video/frikanalen';


if ($ARGV[0] eq 'metarefresh' ){
	$frikanal_meta_subset = &get_frikanalen_meta_subset;
	&meta_refresh;
} elsif ($ARGV[0] eq 'updatevideo') {
	$frikanal_meta_subset = &get_frikanalen_meta_subset;
	&get_new_videos($frikanal_meta_subset);
} else {
	print "Usage: update_local.pl metarefresh|updatevideo \n";
}

####### Functions ####################

sub encode_videos {

}

sub meta_refresh {
 	foreach my $id (keys %$meta_data) {
#	&write_meta_data;
	}
}

sub write_meta_data {
 # write metadata for each movie to $movie_id.desc textfiles
 # The intention is to use these for generating html pages.  
 my $id = $_[0];
 my $meta_data = $_[1];
 open DESCFILE, "> $localvideo_dir/$id.desc" or die "Cannot open $localvideo_dir/$id.desc for write :$!"; 
 foreach my $key (keys %{$meta_data->{$id}}) {
  print DESCFILE "$key\;$meta_data->{$id}->{$key}\n";
 }
 close DESCFILE;
}

sub get_new_videos {
 # Compares all available videos with contents on local video-directory, and 
 # download videos not found locally.
 my @localvideos;
 my @remotevideos;
 my $meta_data =  $_[0];
 opendir LOCALVIDEO_DIR, $localvideo_dir or die "Can't open directory $localvideo_dir: $!\n";
 @localvideos = grep /^.+\.wmv/, readdir(LOCALVIDEO_DIR);
 closedir HOST_DIR;
 foreach my $remote (keys %$meta_data) {
  $exists = 'false';
  foreach my $local (@localvideos) {
   $local =~ s/.wmv//;
   if ($remote eq $local) {
    $exists = 'true'
   }
  }
  if ($exists ne 'true') {
   # wget does not handle mms
   # also mms is a stream that needs to go down in realtime playing of the stream. 
   if  ($meta_data->{$remote}->{'VideoUri'} =~ /^http:/) {
    $r = 1;
    while ($r != 0 ) {
     $r = `wget -r -O "$localvideo_dir/$remote.wmv" $meta_data->{$remote}->{'VideoUri'}`;
    }
    &write_meta_data($remote,$meta_data,$localvideo_dir);
   }
   if  ($meta_data->{$remote}->{'VideoUri'} =~ /^mms:/) {
    $r = 1;
    while ($r != 0 ) {
     $r = `mplayer -dumpstream -dumpfile "$localvideo_dir/$remote.wmv" $meta_data->{$remote}->{'VideoUri'}`;
    }
    &write_meta_data($remote,$meta_data,$localvideo_dir);
   }
  }
 }
}

sub get_frikanalen_meta_subset {
 # Build metadata structure with id as key
 my $returndata;
 $soap = new SOAP::Lite
 -> uri('http://localhost/CommunitySiteService')
 -> proxy('http://communitysite1.frikanalen.tv/CommunitySiteFacade/CommunitySiteService.asmx');

 # Request list of all available videos with all avalable metadata for each video
 # constructing the expected xml code for 
 # http://communitysite1.frikanalen.tv/CommunitySiteFacade/CommunitySiteService.asmx?op=SearchVideos
 # 'Take' is how many records to grab. Just crank it higher than the number of available records,
 # and it will return all. 

 my $obj = $soap->SearchVideos(
  SOAP::Data->name('searcher' => {
   'PredefinedSearchType' => 'Default',
   'Take' => 10,
   }
  )
 );
 unless ($obj->fault) {
  my $res = $obj->result;
  print Dumper($res);
  my $nuug_video_prefix = 'http://www.nuug.no/pub/video/frikanalen/';
  # build a smaller more manageable data structure with id as key. 
  foreach (@{$res->{'Data'}->{'Video'}}) {
    $returndata->{$_->{Id}}->{'VideoUri'} = $_->{'VideoUri'};
    $returndata->{$_->{Id}}->{'ogvUri'} = $nuug_video_prefix.$_->{'Id'}.'.ogv';
    $returndata->{$_->{Id}}->{'oggUri'} = $nuug_video_prefix.$_->{'Id'}.'.ogg';
    $returndata->{$_->{Id}}->{'mpegUri'} = $nuug_video_prefix.$_->{'Id'}.'.mpeg';
    $returndata->{$_->{Id}}->{'mp3Uri'} = $nuug_video_prefix.$_->{'Id'}.'.mp3';
    $returndata->{$_->{Id}}->{'ipodUri'} = $nuug_video_prefix.$_->{'Id'}.'ipod.mov';
    $returndata->{$_->{Id}}->{'Title'} = $_->{'Title'};
   # $returndata->{$_->{Id}}->{'Title'} = $_->{'Title'};
    $returndata->{$_->{Id}}->{'Length'} = $_->{'MetaData'}->{'Length'};
    $returndata->{$_->{Id}}->{'Description'} = $_->{'Description'};
  }
   # $obj->destroy;
  return $returndata;
 } else {
  print join ', ',
  $result->faultcode,
  $result->faultstring;
 }
}
