#!/usr/bin/perl -w
use warnings;
use strict;

use UUID;
use File::HomeDir;
use IO::Socket;
use Net::hostent;
use threads;
use Thread::Queue;

package capture_cameras
{   
    my $server;
    my $queue = Thread::Queue -> new;
    sub new
    {
        my $class = shift;
        my $self = {};
        bless($self, $class);
        return $self;
    }

    sub command
    {
        return "Capture";
    }

    sub doupstart
    {
        return 0;
    }

    sub help
    {
        return "take images from all the cameras connected and output them to ~/DIY_Streetview/images [The directory will be created if it doesn't exist.]";
    }

    sub do
    {
        my $home = File::HomeDir->my_home;
        if (!-d "$home/DIY_Streetview/images")
        {
            if (system ("mkdir $home/DIY_Streetview/images")) { print "Failed to create required folder '~/DIY_Streetview/images'\n"; die(); }
        }
        #UUID is a Universaly Unique IDentifier
        #GUID is a Globaly Unique IDentified
        #GUID is another name for UUID
        #Since $uuid will have the Raw UUID, $guid has the String version of the UUID
        
        my ($uuid, $guid);
        UUID::generate($uuid);
        UUID::unparse($uuid, $guid);
        
        my $gps = $main::settings{'gps'};
        my $location;
        my ($GPSLOGFILE, $time) = (undef,time());
        open $GPSLOGFILE, ">>$home/DIY_Streetview/sets.log" or die "Cannot open GPS logfile: $!";
        
        if (defined($gps) && $gps->hasgps)
        {
            $location = $gps->locsv;
            print $GPSLOGFILE "$time, $guid, $location\n";
        }
        else
        {
            $location = "No GPS Device detected at program start. Storing 0,0.";
            print $GPSLOGFILE "$time, $guid, 0, 0\n";
        }
        
        close $GPSLOGFILE;
        
        #Just so OSs don't choke on to many files in a folder.
        my $imagepath = $guid;
        $imagepath =~ s/-/\//g;
        
        if (!-d "$home/DIY_Streetview/images/$imagepath/")
        {
            my @dirs = split(/\//, $imagepath);
            my $path = "$home/DIY_Streetview/images/";
        
            while (scalar(@dirs) > 0)
            { 
                my $tmp = shift(@dirs);
                $path = "$path/$tmp";
                system ("mkdir $path");
            }
        }

        my @cameras = @{$main::plugins{'camera'}};
        my %settings = %{$main::settings{'camera'}};
        my $focus = $settings{'focus'};
        my $brightness = $settings{'brightness'};
        my $exposure = $settings{'exposure'};
        
        my $count_cameras = 0;
        while ($count_cameras < scalar(@cameras))
        {
            if (!-e "/dev/$cameras[$count_cameras]")
            {
                print "ERROR: Camera ID: $count_cameras has been disconnected! Redetecting cameras.\n";
                print "Aborting Capture!\n";
                return;
            }
            
            if (system("uvcdynctrl -d $cameras[$count_cameras] --set='Focus, Auto' 0;
            uvcdynctrl -d $cameras[$count_cameras] --set='Focus (absolute)' $focus;
            uvcdynctrl -d $cameras[$count_cameras] --set='Brightness' $brightness;
            uvcdynctrl -d $cameras[$count_cameras] --set='Exposure, Auto' 1;
            uvcdynctrl -d $cameras[$count_cameras] --set='Exposure (Absolute)' $exposure;"))
            {
                print "WARNING: Camera initilisation returned errors!\n";
            }
            
            my $device_path = `udevadm info --query=path -n /dev/$cameras[$count_cameras]`;
            my @device_info = split(/\//, $device_path);
            #If my webcams could support it I would make a way for the cameras to be just as cool as Rainbow Dash
            if (system("avconv -f video4linux2 -i /dev/$cameras[$count_cameras] -t 1 -vframes 1 -s hd1080 -vsync 1 -an $home/DIY_Streetview/images/$imagepath/image_$device_info[6].png -loglevel 'error' > /dev/null"))
            {
                print $main::socket "{ \"success\":false }\n";
                die(1);
            }
	    else
	    {
		print $main::socket "{ \"captured\":",$count_cameras + 1," }\n";
	    }
            
            $count_cameras++;
        }
        print $main::socket "{ \"success\":true, \"set\":\"",$guid,"\" }\n";
        print "Captured set $guid\n";
    }
    
    sub defaultsettings
    {
        return undef;
    }

1;
}
