# Copyright © 2010 Thomas Schwinge <thomas@schwinge.name>

# 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; either version 2, or (at your option) any later
# version.
# 
# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.

package IkiWiki::Plugin::absorb;

use warnings;
use strict;
use IkiWiki 3.00;

sub import
{
    hook(type => "preprocess", id => "absorb", call => \&absorb);
}

sub absorb (@)
{
    my %params = @_;

    foreach my $param (qw{pagenames})
    {
	if (! exists $params{$param})
	{
	    error (sprintf (gettext ('%s parameter is required'), $param));
	}
    }

    foreach my $page (split(' ', $params{pagenames}))
    {
	my $bestpage = bestlink ($params{page}, $page);
	error (sprintf (gettext ('no such page: %s'), $page)) unless length($bestpage);

	#TODO: page or destpage?
	add_depends ($params{page}, $page);

	my $content = readfile (srcfile ($pagesources{$bestpage}));

	IkiWiki::preprocess ($params{page}, $params{destpage},
			     IkiWiki::filter ($params{page}, $params{destpage},
					      $content));

#	IkiWiki::run_hooks (scan => sub {
#	    shift->(
#		page => $params{page},
#		content => $content,
#		);
#	    });
#
#	# Preprocess in scan-only mode.
#	IkiWiki::preprocess($params{page}, $params{page}, $content, 1);
    }

    return "" if defined wantarray;
}

1;
