#!/usr/bin/perl

use strict;
use File::Spec;
use File::BaseDir;
use Gtk2 '-init';
use Zim;
use Zim::Repository;

my ($root, $page, $doc);
my $data_dir = find_data_dir();
my $settings = {
	read_only => 0,
	data_dir  => $data_dir,
	icon_file => File::Spec->catfile($data_dir, qw/images zim64.png/),
};

while ($ARGV[0] =~ /^-/) {
	$_ = shift @ARGV;
	
	if (/^(--version|-v)$/) {
		print $Zim::LONG_VERSION;
		exit;
	}
	elsif (/^--read-?only$/) { $$settings{read_only} = 1 }
	elsif (/^--doc$/) {
		$root = File::Spec->catdir($data_dir, 'doc');
		($doc, $$settings{read_only}) = (1, 1);
	}
	elsif (/^--export$/) {
		$$settings{export} = shift @ARGV;
	}
	elsif (/^--?\w/) { exit_usage() } # include --help etc.
	
	last if /^--?$/;
}


my $zim = Zim->new($settings);

$root = shift @ARGV unless defined $root;
$root = $$settings{default_root} unless defined $root;
exit_usage() unless defined $root;

$page = shift @ARGV;
exit_usage() if @ARGV;

my $rep = Zim::Repository->new('', $root);
$zim->set_repository($rep);
$$settings{root_dir} = $root;

export($$settings{export})
	if exists $$settings{export};

$zim->gui_init;

my $home = $$settings{default_home};
{
	if (defined $doc) {
		$page = 'Help' unless defined $page;
		$home = 'Help';
	}
	my $current = $zim->History->current;

	unless (length $page) { # no commandline arg
		if ($current) { $zim->load_page($current) }
		else {
			$zim->load_page($home);
			$zim->History->push($zim->{page});
		}
	}
	elsif ($current->{name} eq $page) {
		$zim->load_page($current);
	}
	else {
		$zim->load_page($page);
		$zim->History->push($zim->{page});
	}
	$zim->signal_emit('history_changed');
}
$$settings{home} = $home;

$zim->PageView->grab_focus;
$zim->main_loop;

exit;

sub find_data_dir {
	my ($data_dir) =
		grep { -d $_ && -r $_ }
		map  { File::Spec->catdir($_, 'zim') }
		( File::BaseDir->xdg_data_home, File::BaseDir->xdg_data_dirs );

	unless ($data_dir) {
		my @dirs = File::Spec->splitdir($0);
		pop @dirs; pop @dirs;
		my $dir = File::Spec->catdir(@dirs, 'share', 'zim');
		$data_dir = $dir if -d $dir and -r $dir;
	}

	return $data_dir if defined $data_dir;
	
	print << 'EOT';
Could not find data files.
Typically these should be found in a dir like 
    /usr/share/zim/         or
    /usr/local/share/zim/

If you have found the directory try adding the base
part of the directory ('/usr/share/' for '/usr/share/zim') 
to the XDG_DATA_DIRS variable.
EOT
	exit 1;
}

sub exit_usage {
	print << "EOT";
Usage: $0 ROOT_DIR [PAGE]

  ROOT_DIR is the directory to store all docs, for example ~/zim/
  PAGE     is the page you want to open, this argument is optional

  To view the manual try "$0 --doc"
EOT
	exit;
}

sub export { # FIXME needs it's own module
	my $string = shift;
	my %opts = map split('=', $_, 2), split ',', $string;
	for (qw/format template root/) {
		die "zim: for exporting you need at least to provide a format a template and an output root dir.\n" unless length $opts{$_};
	}

	my $namespace = ($page =~ /:$/) ? $page : '';
	my $exporter = Zim::Repository->new('', $opts{root}, $opts{format});
	$exporter->{template} = $opts{template};
	
	my $r = defined($opts{recurs}) ? $opts{recurs} : 1 ;
	if (length $namespace) { export_namespace($rep, $exporter, $page, $r) }
	else                   { export_page($rep, $exporter, $page)          }

	exit 0;
}

sub export_namespace {
	my ($rep, $exporter, $page, $r) = @_;
	
	my $index = 1;
	my @pages = $rep->list_pages($page);
	for (@pages) { # FIXME recursive option
		$index = 0 if /index/;
		export_namespace($rep, $exporter, "$page$_", $r) if $r and /:$/;
		export_page($rep, $exporter, "$page$_") or $_ = undef;
	}
	@pages = grep defined($_), @pages;

	if ($index) {
		print "Writing index\n";
		$index = Zim::Page::File->new($exporter, $page.'index');
		$index->push_blocks(
			['head1', {}, "Document index for $page"] );
		$index->push_blocks(
			['Para', {},
				map {("* ", ['L', {to => $_}, $_])} @pages
			]
		);
		$exporter->save_page($index);
	}
	
}

sub export_page {
	my ($rep, $exporter, $page) = @_;
	
	my $obj = $rep->load_page($page);
	return 0 if $obj->status eq 'new';
	print "Exporting: $page\n";
	$exporter->save_page($obj);
	return 1;
}

1;

__END__

=head1 NAME

zim - A desktop wiki

=head1 SYNOPSIS

zim [options] root_dir [page_name]

=head1 DESCRIPTION

Try to execute C<zim --doc> to view the user manual.

=head1 OPTIONS

... FIXME ...

=head1 AUTHOR

Jaap Karssenberg E<lt>pardus@cpan.orgE<gt>

Copyright (c) 2005 Jaap G Karssenberg and RL Zwart. All rights
reserved. This program is free software; you can redistribute it and/or
modify it under the same terms as Perl.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MER-
CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either the GNU
General Public License or the Artistic License for more details.

=head1 SEE ALSO

L<Zim>(3)

=cut
