#!/usr/bin/perl -X -T
################################################################################
#          _____ _
#         |_   _| |_  ___
#           | | | ' \/ -_)
#           |_| |_||_\___|
#                   _   _             ____            _           _
#    / \   _ __ ___| |_(_) ___ __ _  |  _ \ _ __ ___ (_) ___  ___| |_
#   / _ \ | '__/ __| __| |/ __/ _` | | |_) | '__/ _ \| |/ _ \/ __| __|
#  / ___ \| | | (__| |_| | (_| (_| | |  __/| | | (_) | |  __/ (__| |_
# /_/   \_\_|  \___|\__|_|\___\__,_| |_|   |_|  \___// |\___|\___|\__|
#                                                  |__/
#          The Arctica Modular Remote Computing Framework
#
################################################################################
#
# Copyright (C) 2015-2016 The Arctica Project
# http://http://arctica-project.org/
#
# This code is dual licensed: strictly GPL-2 or AGPL-3+
#
# GPL-2
# -----
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
#
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# AGPL-3+
# -------
# This programm is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This programm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# Copyright (C) 2015-2016 Guangzhou Nianguan Electronics Technology Co.Ltd.
#                         <opensource@gznianguan.com>
# Copyright (C) 2015-2016 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
#
################################################################################
# WARNING THIS IS A HYBRID BASTARD MIX (of 3 generations of AWB)
use strict;
use Data::Dumper;
use Arctica::Core::eventInit qw(genARandom BugOUT);
use Arctica::Core::JABus::Socket;
use POSIX qw(mkfifo);
use Gtk3 -init;
use Glib;
use Glib::Object::Introspection;
use Glib qw(TRUE FALSE);

use Arctica::Browser::ToolBar;
use Arctica::Browser::WebView;
use Arctica::Browser::Proxy;

use X11::Protocol;
use X11::GUITest qw(RaiseWindow SetInputFocus);
my $X11 = X11::Protocol->new();

Glib::Object::Introspection->setup(
	basename => "GdkX11",
	version => "3.0",
	package => "Gtk3::Gdk");

my $proxy = Arctica::Browser::Proxy->new;
my $gnx_xid;
if ($ENV{'TEKINXWID'} =~ /^([\da-zA-Z]{4,})$/) {
        $gnx_xid = hex $1;
	BugOUT(8,"NX WID: $gnx_xid");
} else {
        BugOUT(0,"did not get the clientnxwid via ENV{'TEKINXWID'}");
}

unless (-x "/usr/bin/xdotool") {
        BugOUT(0,"Are we missing xdotool '/usr/bin/xdotool'?");
}

my $lastcontact = (time + 5);

my $ACO = Arctica::Core::eventInit->new({
	app_name=>'arctica-browser-overlay',
	app_class =>'amoduletester',
	app_version=>'0.0.0.2'});

my $app_id = @ARGV[0];
my $ttid = @ARGV[1];
my $sock_id;
my $wizi = 0;
my $wizy = 0;
my $wizx = 0;
if (@ARGV[2] =~ /^([a-zA-Z0-9]*)$/) {
	$sock_id = $1;
	BugOUT(8,"SOC:\t$sock_id");
} else {BugOUT(0,"YOU SOCK!");}

my $rwid;
if (@ARGV[4] =~ /^([a-zA-Z0-9\_\-]*)$/) {
	 $rwid = $1;
	warn("REAL WID: $rwid");
}

my $TeKi = Arctica::Core::JABus::Socket->new($ACO,{
	type	=>	"unix",
	destination =>	"local", # FIX ME (change to remote!!!)
	is_client => 1,
	connect_to => $sock_id,
	handle_in_dispatch => {
			chtstate => sub {\&chtargetstate(@_)},
	},
	hooks => {
		on_ready => sub {my_ready($app_id,$ttid);},
		on_client_errhup => sub {BugOUT(0,"\tLOST CONN!\n");},
	},

});

my $timeout = Glib::Timeout->add(100, sub {
	if ($lastcontact < (time-5)) {
		BugOUT(0,"We're an orphan?");
	}
	return 1;
});

my $window = Gtk3::Window->new('popup');
$window->set_default_size(80, 60);
$window->set_title('Browser');
$window->signal_connect(destroy => sub { Gtk3->main_quit() });

my $toolbar = Arctica::Browser::ToolBar->new;
my $webview = Arctica::Browser::WebView->new($toolbar);

my $vbox = Gtk3::Box->new( 'vertical', 0);
$vbox->set_border_width(0);
$vbox->pack_start($toolbar->return_toolbar,FALSE,FALSE,0);
$vbox->pack_start($webview->return_webview,TRUE,TRUE,0);
$window->add($vbox);

$window->show_all();
$window->map();
$window->unmap();
my $overlaywinid = $window->get_window->get_xid;
system("/usr/bin/xdotool","windowreparent",$overlaywinid,$gnx_xid);
$ACO->{'Glib'}{'MainLoop'}->run;


sub chtargetstate {
	my $data = $_[0];
	$lastcontact = time();
	warn(Dumper($data));
	my $x = $data->{'apx'};
	my $y = $data->{'apy'};

	if ($data->{'w'} and $data->{'h'}) {
		$window->resize($data->{'w'},$data->{'h'});

	}

	if ((defined $x) and (defined $y)) {

		$wizx = $x;
		$wizy = $y;
		if ($data->{'visible'} eq 1) {
			$window->move($wizx,$wizy);
		}
	}


	if ($data->{'visible'} eq 1) {
		if ($wizi ne 1) {

			$window->map();
			$window->move($wizx,$wizy);
system("/usr/bin/xdotool","windowreparent",$window->get_window->get_xid,$gnx_xid);

RaiseWindow($window->get_window->get_xid);
SetInputFocus($window->get_window->get_xid);

			$wizi = 1;
		}
	} else {
$wizi = 0;
			$window->move(0,0);
system("/usr/bin/xdotool","windowreparent",$window->get_window->get_xid,$rwid);
#		$window->unmap();
	}
}

sub my_ready {
	BugOUT(8,"MY READY?");
	my $app_id = $_[0];
	my $ttid = $_[1];
	$TeKi->client_send('treg',{
				app_id => $app_id,
				ttid => $ttid,
	});
}


sub daemonize {
	fork and exit;
	POSIX::setsid();
	fork and exit;
	umask 0;
	chdir '/';
	close STDIN;
	close STDOUT;
	close STDERR;
}
