package App::Wack;
use strict;
use warnings;

use Gtk2 -init;
use Gtk2::GladeXML;
use App::Ack;
use App::Wack::Glade;

our $VERSION = '0.01';

my $gladexml;

sub run {
    my ($class) = @_;
     
    $gladexml = Gtk2::GladeXML->new_from_buffer(App::Wack::Glade::get_xml());
    $gladexml->signal_autoconnect_from_package("App::Wack");

    Gtk2->main;
}

AUTOLOAD {
    our $AUTOLOAD;
	print $AUTOLOAD . "\n";
}
sub DESTROY {
}

sub on_help_clicked {

    # TODO: get the copyright from ack automatically
    #my $ack_copyrioght = App::Ack::version_statement($COPYRIGHT);
    my $help = <<"END_HELP";
This is version $VERSION of wack
Using ack version $App::Ack::VERSION

wack is Copyright 2007 Gabor Szabo http://search.cpan.org/dist/App-Wack
ack is Copyright 2005-2007 Andy Lester http://search.cpan.org/dist/App-Ack
END_HELP
    _set_result($help);
    return;
}

sub _set_result {
    my ($text) = @_;

    my $result = $gladexml->get_widget('results')->get_buffer;
    $result->delete($result->get_start_iter, $result->get_end_iter,);
    $result->set_text($text);  
    return;
}

sub on_search_activate {
    on_search_clicked();
}

sub on_search_clicked {
    my $result = $gladexml->get_widget('results')->get_buffer;
    my $search = $gladexml->get_widget('search-text');
    my $text = $search->get_text;
    my $out = '';
    ack($text, sub {$out .= shift});
    _set_result($out); 
}

sub on_main_destroy {
	Gtk2->main_quit;
    exit;
}
sub on_quit_clicked {
	Gtk2->main_quit;
    exit;
}

sub ack {
    my ($str, $cb) = @_;
    open (my $ACK, "ack $str |") or die;
    while (my $line = <$ACK>) {
        $cb->($line);
    }
}

# called when packaging the application
sub create_glade {
    open my $glade, '<', 'glade/wack.glade' or die;
    local $/ = undef;
    my $xml = <$glade>;
    mkdir 'lib/App/Wack';
    open my $out, '>', 'lib/App/Wack/Glade.pm' or die;
    print $out <<"END_GLADE";
package App::Wack::Glade;
use strict;
use warnings;

# this is an autogenerated file

sub get_xml {
    return <<"END_XML";
$xml
END_XML

}
1;
END_GLADE

    exit;
}


=head1 NAME

App::Wack - the actual code of wack the wisual ack

=head1 SYNOPSIS

You should only use the 

 wack

command and not the module itself.

=head1 DESCRIPTION

App::Wack is the implementation of the Gtk2 and GladeXML based 
GUI around L<ack>, the grep-like text finder.

=head1 DEVELOPMENT

Subversion repository:
L<http://svn1.hostlocal.com/szabgab/trunk/wack/>

Bugs L<https://rt.cpan.org/> 
Email: bug-app-wack to rt.cpan.org

=head1 COPYRIGHT

Copyright 2007 Gabor Szabo, all rights reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=cut

1;

