#!/usr/bin/perl
use LWP::Simple;

my $script_name = "kodinp";
my $author = "multiple";
my $version = "0.1";
my $license = "Public domain";
my $description = "Get current song from kodi";


weechat::register($script_name, $author, $version, $license, $description, "", "");
weechat::hook_command("kodi", "Get current song from kodi", "", "", "", "kodi", "");

# Config
my $ip = "192.168.1.10";
my $port = "8080";

# Declare vars
my $artist;
my $title;
my $album;
my $np;

# Get NP data method
sub kodi {
        # Get now playing from xbmc
        my $content = get("http://192.168.1.10:8080/jsonrpc?request={%22jsonrpc%22:%20%222.0%22,%20%22method%22:%20%22Player.GetItem%22,%20%22params%22:%20{%20%22properties%22:%20[%22title%22,%20%22album%22,%20%22artist%22,%20%22season%22,%20%22episode%22,%20%22duration%22,%20%22showtitle%22,%20%22tvshowid%22,%20%22thumbnail%22,%20%22file%22,%20%22fanart%22,%20%22streamdetails%22],%20%22playerid%22:%201%20},%20%22id%22:%20%22VideoGetItem%22}");
        die "get failed" if (!defined $content);

        # Get now playing
        if($content =~ m/"artist":\[(.*?)\]/i) {
                $artist = $1;
                $artist =~ s/"//g;
        }
        if($content =~ m/"title":"(.*?)"/i) {
                $title = $1;
        }
        if($content =~ m/"album":"(.*?)"/i) {
                $album = $1;
    }

        # Set NP var
        if (!defined $artist){
                $np = $title;
        } else {
                $np = $artist . " - " . $title . " (" . $album . ")";
        }

        # Unset vars
        undef $title;
        undef $artist;
    undef $album;

        # Output to active window in weechat
        if (defined $np){              
                weechat::command("", "/me np: $np");
        }
        return 1;
}
