#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use File::ChangeNotify;
use Time::HiRes qw( sleep );

my $max_width = 800;
my $max_height = 600;

my $dir = '/opt/pos/common/tmp/opened_windows';
mkdir($dir) unless -d $dir;

my $watcher = File::ChangeNotify->instantiate_watcher(
  directories => $dir,
);

while (my @events = $watcher->wait_for_events()) {
  foreach my $e (@events) {
    next unless $e->type() eq 'create' || $e->type() eq 'modify';

    my( $name, $width, $height ) = $e->path() =~ /^.*\/(.*?)#(\d+)#(\d+)$/;
    #print STDERR "#### $name - $width - $height\n";
    next unless defined $name && defined $width && defined $height;

    my $pos_w = int(($max_width / 2) - ($width / 2));
    my $pos_h = int(($max_height / 2) - ($height / 2));

    sleep 0.1;
    system("export DISPLAY=:0.0 ; wmctrl -r \"$name\" -e 0,$pos_w,$pos_h,-1,-1");
    # unlink $e->path();
  }
}


