# Merge Search Results plugin for Movable Type
# Copyright (c) Ailin "Nei" Nemui, https://anti.teamidiot.de/
# Released under the same terms as Perl itself.

package MT::Plugin::MergedSearch;
use strict;
use MT 4;

use base qw( MT::Plugin );
our $VERSION = 0.2;

MT->add_plugin(__PACKAGE__->instance);

sub instance {
	(grep { ref $_ eq __PACKAGE__ } @MT::Components)[0] ||
	__PACKAGE__->new({
			id				=> 'MergedSearch',
			name			=> 'Merge Search Results',
			version		=> $VERSION,
			author_name	=> 'Ailin &ldquo;Nei&rdquo; Nemui',
			author_link	=> 'https://anti.teamidiot.de/',
			description	=> '<MT_TRANS phrase="' .
								'Flattens search results across multiple Blogs ' .
								'into a single one instead of the default ' .
								'grouping behaviour.' .
								'">',
			system_config_template => sub {
				my %h = ( 0 => 'UNLESS', 1 => 'IF' );
				my $r = '';
				for my $o (
					[_tag_search => 'Tag Search'],
					[_regular => 'Regular Search']
				) {
					$r .= <<"TMPL";
<mtapp:setting id="merge$o->[0]" label="<__trans phrase="$o->[1]">">
<ul>
TMPL
					for my $i (
						[0 => 'Do not merge'],
						[1 => 'Merge']
					) {
						$r .= <<"TMPL";
<li><input type="radio" name="merge$o->[0]" value="$i->[0]" id="merge$o->[0]$i->[0]" class="rb"<TMPL_$h{$i->[0]} NAME=MERGE\U$o->[0]\E> checked="checked"</TMPL_$h{$i->[0]}> /> <label for="merge$o->[0]$i->[0]"><MT_TRANS phrase="$i->[1] $o->[1] results"></label></li>
TMPL
					}
					$r .= <<"TMPL";
</ul>
</mtapp:setting>
TMPL
				}
				$r
			}->(),
			settings		=> MT::PluginSettings->new([
				[ merge_tag_search	=> { Default => 0, Scope => 'system' } ],
				[ merge_regular		=> { Default => 0, Scope => 'system' } ]])})
}

sub __merge {
	my $_continue = shift;
	my ($setting) = @_;
	sub {
		my ($app) = @_;
		my $res = &$_continue;

		my $d = +{ map { lc$_ => 1 } split /\s*,\s*/,
				$app->config->NoOverride }->{merge} ? undef
			: $app->param('merge');

		$d = __PACKAGE__->instance->get_config_value(
			"merge$setting", 'system' ) unless defined $d;

		$app->{results} = {'' => [
			sort { $b->{entry}->authored_on() <=> $a->{entry}->authored_on() }
			map { @{ $app->{results}{$_} } }
				keys %{ $app->{results} } ]}
					if $d && $app->{results} =~ /HASH/;
		$res;
	}
}

{
	*MT::App::Search::_tag_search = __merge(
		\&MT::App::Search::_tag_search, '_tag_search');
	*MT::App::Search::_straight_search = __merge(
		\&MT::App::Search::_straight_search, '_regular');
}

1;

