package Newslash::Plugin::ResponseFilter;
use Mojo::Base 'Mojolicious::Plugin';
use Data::Dumper;

sub register {
    my ($self, $app, $conf) = @_;

    # set default config value
    my $cnf = $app->config->{ResponseFilter} ||= {};
    my $default_faculities = { users => { 10000 => [qw(realemail passwd newpasswd newpasswd_ts)] },
                               comments => { 1000 => [qw(ipid subnetid)] },
			       metamoderations => { 1000 => [qw(uid)] },
			       moderations => { 1000 => [qw(ipid subnetid uid m2uid)] },
			       stories => { 1000 => [qw(hits hitparade)] },
			       submissions => { 1000 => [qw(ipid subnetid note comment)] },
			     };
    $cnf->{faculities} ||= $default_faculities;
    $cnf->{enable} //= 0;
    $app->helper(apply_seclev_filter => sub { apply_seclev_filter(@_) });

    if ($cnf->{enable}) {
	$app->hook(before_render => sub {
		       my ($c, $args) = @_;
		       return if (!defined $args->{json});

		       my $json = $args->{json};
		       my $result = $json;
		       if (defined $json->{result} && ref($json->{result}) eq "HASH") {
			   $result = $json->{result};
		       }

		       if ($result->{item}) {
			   my $type = $result->{item}->{content_type};
			   if ($type) {
			       apply_seclev_filter($c, $type, $result->{item});
			   }
		       }

		       if ($result->{items} && ref($result->{items}) eq "ARRAY") {
			   for my $item (@{$result->{items}}) {
			       my $type = $item->{content_type};
			       if ($type) {
				   apply_seclev_filter($c, $type, $item);
			       }
			   }
		       }
		   });
    }
}

sub apply_seclev_filter {
    my ($c, $model, $items) = @_;
    if (!$items || !$model) {
        $c->app->log->error("ResponseFilter: model or items not given");
        return;
    }

    my $user = $c->stash('user') || {};
    my $security_level = $user->{seclev} || 0;

    my $targets = $items;
    if (ref($items) ne "ARRAY") {
        $targets = [$items];
    }

    my $cnf = $c->config->{ResponseFilter} || {};
    my $faculties = $cnf->{faculities} || {};

    my $faculty_all = $faculties->{all} || {};
    for my $lv (keys %$faculty_all) {
        if ($security_level < $lv) {
            for my $item (@$targets) {
                for my $k (@{$faculty_all->{$lv}}) {
                    if (defined $item->{$k}) {
			delete $item->{$k};
			#$c->app->log->debug("remove $k");
		    }
                }
            }
        }
    }

    my $faculty = $faculties->{$model} || {};
    for my $lv (keys %$faculty) {
        if ($security_level < $lv) {
            for my $item (@$targets) {
                for my $k (@{$faculty->{$lv}}) {
                    if (defined $item->{$k}) {
			delete $item->{$k};
			#$c->app->log->debug("remove $k");
		    }
                }
            }
        }
    }


    return $items;
}

1;
