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

use JSON::XS qw{};
use IO::Socket::INET6 qw{};

package gpsd
{
    local ($gpsd::hasgps, $gpsd::self) = (1);
    my ($json, $socket) = (JSON::XS->new, IO::Socket::INET6->new(PeerAddr => '127.0.0.1',PeerPort => '2947'));
    sub new
    {
        my $class = shift;
        $gpsd::self = {};
        bless($gpsd::self, $class);
        return $gpsd::self;
    }

    sub name
    {
        return "GPSD";
    }


    sub doupstart
    {
        return 1;
    }

    sub upstart
    {
        print "Detecting if GPSD is running...\n";
        if (!defined($socket))
        {
            $gpsd::hasgps = 0;
        }
        else
        {
            $gpsd::hasgps = 1;
            $socket->send("?WATCH={\"enable\":true};\n");
            my $line;
            $line = $socket->getline;
            $line = $socket->getline;
            $line = $socket->getline;
        }
        if ($gpsd::hasgps)
        {
            print "GPSD detected... Enabling Location awareness...\n";
            undef($main::settings{'gps'});
            $main::settings{'gps'} = $gpsd::self;
            print "GPS configured.\nLocation awareness enabled.\n";
            
        }
        else
        {
            print "GPSD not running, Not enabling GPSD location awareness.\n";
        }
    }
    
    sub location
    {
            $socket->send("?POLL;\n");
            my $line;
            $line = $socket->getline;

            if (defined($line))
            {
            chomp $line;
            my %data = %{ $json->decode($line)};
            my %tpv = %{$data{'tpv'}[0]}; 
            my ($lat, $lon) = ($tpv{'lat'}, $tpv{'lon'});
            return "Lat: $lat, Lon: $lon";
            }
            else
            {
            return "GPSD Didn't respond. Is it running?";
            }
    }
    
    sub locsv
    {
            $socket->send("?POLL;\n");
            my $line;
            $line = $socket->getline;

            if (defined($line))
            {
            chomp $line;
            my %data = %{ $json->decode($line)};
            my %tpv = %{$data{'tpv'}[0]}; 
            my ($lat, $lon) = ($tpv{'lat'}, $tpv{'lon'});
            return "$lat, $lon";
            }
            else
            {
            return "0,0";
            }
    }
    
    sub hasgps
    {
        return $gpsd::hasgps;
    }
    
    sub defaultsettings
    {
        return undef;
    }
1; #Yay Packages having to end with a 1!
}
