#!/usr/bin/env perl

use strict;
use warnings;

use App::Asciio::Text::Asciio ;

use Module::Util qw(find_installed) ;
use File::Basename ;

#-----------------------------------------------------------------------------

my $asciio = App::Asciio::Text->new(50, 25) ;

my ($command_line_switch_parse_ok, $command_line_parse_message, $asciio_config)
	= $asciio->ParseSwitches([@ARGV], 0) ;

die "Error: '$command_line_parse_message'!" unless $command_line_switch_parse_ok ;

my $setup_paths = [] ;

if(@{$asciio_config->{SETUP_PATHS}})
	{
	$setup_paths = $asciio_config->{SETUP_PATHS} ;
	}
else
	{
	my ($basename, $path, $ext) = File::Basename::fileparse(find_installed('App::Asciio'), ('\..*')) ;
	my $setup_path = $path . $basename . '/setup/' ;
	
	$setup_paths = 
		[
		$setup_path . 'setup.ini', 
		$setup_path . 'Text/setup.ini', 
		$ENV{HOME} . '/.config/Asciio/Asciio.ini',
		] ;
	}

my $title = $asciio_config->{TARGETS}[0] ;
$asciio->run_actions_by_name(['Open', $title]) if defined $title ;

# 'open' deserializes an asciio object with it's attributes, if the file
# was saved by a different asciio object (GUI/TUI), the attributes in
# the serialized object will not fit, run setup after 'open'
$asciio->setup($setup_paths) ;

$asciio->set_title($title) if defined $title ;
$asciio->{ACTION_VERBOSE} = sub { $asciio->{LAST_ACTION} = $_[0] ; } ;

my ($character_width, $character_height) = $asciio->get_character_size() ;

$asciio->set_modified_state(0) ;
$asciio->run_script($asciio_config->{SCRIPT}) ;

#--------------------------------------------------------------------------

use Term::ReadKey;
use Term::TermKey qw(FLAG_UTF8 RES_EOF FORMAT_VIM FORMAT_LONGMOD);
 
my $tk = Term::TermKey->new(\*STDIN);
$asciio->{CACHE}{TK} = $tk ;
 
# ensure perl and libtermkey agree on Unicode handling
binmode( STDOUT, ":encoding(UTF-8)" ) if $tk->get_flags & FLAG_UTF8; 

$asciio->update_display() ;

print "\e[?1003h" ; # get mouse events

while (1)
	{
	$tk->waitkey(my $key);
	 
	if ( $key->type_is_mouse )
		{
		my ($ev, $button, $line, $col) = $tk->interpret_mouse( $key );
		
		if ($ev == 1 && $button == 1)
			{
			$asciio->run_actions_by_name("Mouse left-click") ;
			}
		
		if ($ev == 3)
			{
			@$asciio{'MOUSE_X', 'MOUSE_Y'} = ($col - 1, $line - 1) ;
			$asciio->update_display() if $asciio->{MOUSE_TOGGLE} ;
			}
		}
	else
		{
		my $key_name = $tk->format_key($key, 0) ;
		
		$asciio->key_press_event($key_name, '') ;
		}
	}

