#!/usr/bin/perl
use strict;
use warnings;
use lib '/home/dakkar/perl5/lib/perl5';
use Net::DBus;

{my $pidgin;
 sub setup {
     #Xchat::print('broad_away::setup called');
     my $bus=Net::DBus->find()
         or return;
     my $pidgin_s=$bus->get_service('im.pidgin.purple.PurpleService')
         or return;
     $pidgin=$pidgin_s->get_object('/im/pidgin/purple/PurpleObject',
                                   'im.pidgin.purple.PurpleInterface')
         or return;
 }
 sub pidgin {
     setup unless $pidgin;
     return $pidgin;
 }
}

my $prev_status;
sub set_away {
    my $pidgin=pidgin or return Xchat::EAT_NONE;

    $prev_status=$pidgin->PurpleSavedstatusGetCurrent()
        unless defined $prev_status;

    my $status= $pidgin->PurpleSavedstatusFind($_[1][1])
        || $pidgin->PurpleSavedstatusFindTransientByTypeAndMessage(5,$_[1][1]);
    if (!$status) {
        $status=$pidgin->PurpleSavedstatusNew(undef,5); # away
        $pidgin->PurpleSavedstatusSetMessage($status,$_[1][1]);

    }
    $pidgin->PurpleSavedstatusActivate($status);
    return Xchat::EAT_NONE;
}

sub set_back {
    my $pidgin=pidgin or return Xchat::EAT_NONE;

    if ($pidgin->PurpleSavedstatusGetType(
        $pidgin->PurpleSavedstatusGetCurrent()) != 5) {
        # if pidgin is not "away", don't touch it
        return Xchat::EAT_NONE;
    }

    my $status;
    if (!defined $prev_status) {
        $status=$pidgin->PurpleSavedstatusFindTransientByTypeAndMessage(2,undef);
    }
    else {
        $status=$prev_status;
        $prev_status=undef;
    }
    $pidgin->PurpleSavedstatusActivate($status);
    return Xchat::EAT_NONE;
}

Xchat::register('broad away','0.2','broadcast the away status onto Pidgin');

Xchat::hook_command('away',\&set_away);
Xchat::hook_command('back',\&set_back);

