#! /usr/bin/perl

#------------------------------------------------------------------------------
# This script is used for publishing notification in mattermost for Automatic in university tickets
#
# Author: Michal Cech <cech@ics.muni.cz>
#
# $Id:$
#------------------------------------------------------------------------------

package RT::Action::SerializeTransaction;
use strict;
use warnings;

use base qw(RT::Action);

use JSON;
use RT::REST2::Util;
use Data::Dumper;
use Socket;

sub write_to_socket {
    my $data = shift;

    my $path = '/var/run/vector/vector_rt.sock';
    require IO::Socket::UNIX;
    my $socket = IO::Socket::UNIX->new(
        Peer => $path,
        Type => SOCK_STREAM()
    );

    die "Could not create socket: $!n" unless $socket;
    my $jsonized = JSON::to_json($data);
    print $socket $jsonized;


}

sub Commit {
    my $self       = shift;
    
    my $serialized = RT::REST2::Util::serialize_record($self->TransactionObj);
    if ($self->TicketObj) {
        $serialized->{'TicketObj'} = RT::REST2::Util::serialize_record($self->TicketObj);
	$serialized->{'Queue'} = $self->TicketObj->QueueObj->Name;
	my $first_attachment = $self->TransactionObj->Attachments->First || undef;
	if (defined $first_attachment) {
  	    $serialized->{'Interface'} = $self->TransactionObj->Attachments->First->GetHeader('X-RT-Interface') || undef;
	}
    }
    if ($self->TransactionObj->Type eq 'CustomField') {
	$serialized->{'OldValue'} = $self->TransactionObj->OldValue;
	$serialized->{'NewValue'} = $self->TransactionObj->NewValue;
    }
    write_to_socket($serialized);
    # if ($serialized->{'Queue'} =~ m/Reviews|Findings/) {
    #    $RT::Logger->debug(Dumper($serialized));
    #}
    return 1;
}
1;
