#/*
# *  Copyright 2007 hkrn <hikarin@users.sourceforge.jp>
# *
# *  Licensed under the Apache License, Version 2.0 (the "License");
# *  you may not use this file except in compliance with the License.
# *  You may obtain a copy of the License at
# *
# *      http://www.apache.org/licenses/LICENSE-2.0
# *
# *  Unless required by applicable law or agreed to in writing, software
# *  distributed under the License is distributed on an "AS IS" BASIS,
# *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# *  See the License for the specific language governing permissions and
# *  limitations under the License.
# */
#
# $Id: message.pm 1265 2007-10-04 14:11:51Z hikarin $
#

package Zeromin2::App::message;

use strict;
use Zeromin::Message qw();
use Zeromin2::Util qw();

sub load {
    _load(
        'get_unread',
        {   IsUnreadMode => 1,
            Method       => 'load',
        },
        @_
    );
}

*load_unread = \&load;

sub load_read {
    _load(
        'get_read',
        {   IsReadMode => 1,
            Method     => 'load_read',
        },
        @_
    );
}

sub load_all {
    _load(
        'receive',
        {   IsAllMode => 1,
            Method    => 'load_all',
        },
        @_
    );
}

sub _load {
    my ( $methodName, $param, $zApp ) = @_;
    $zApp->privilege() or return $zApp->return_value( 1, [] );
    $zApp->add_template_param($param);

    my $zUser    = $zApp->user();
    my $zMessage = Zeromin::Message->new( $zApp->kernel() );
    my $method   = $methodName . '_with_page';
    my $ret      = [];

    $zMessage->set_sender( $zUser->get_current_user()->{id} );
    my ( $messages, $page )
        = $zMessage->$method( $zApp->page_param('message') );

    for my $message (@$messages) {
        my $from = $message->{from};
        my $sent = $message->{sent};
        $message->{from}    = $zUser->get_user($from)->{name};
        $message->{from_id} = $message->{is_all} ? '*' : $from;
        $message->{sent}    = Zeromin2::Util::format_date($sent);
        $message->{sent_ts} = $sent;
        push @$ret, $message;
    }

    return $zApp->return_value( 0, $ret, $page );
}

sub read {
    my ($zApp) = @_;
    $zApp->privilege() or return $zApp->return_value(1);

    my $zUser    = $zApp->user();
    my $iRequest = $zApp->request();
    my $zMessage = Zeromin::Message->new( $zApp->kernel() );
    my $id       = $iRequest->param_int('id');
    my $from     = $iRequest->param('from');
    my $to       = $zUser->get_current_user()->{id};
    my $message  = $zMessage->read( $id, $to, $from );
    my $sent     = $message->{sent};
    my $comment = Img0ch::Kernel::escape_html_entities( $message->{message} );
    $comment =~ s{\n}{<br />}gxms;

    $zApp->add_template_param(
        {   From    => $zUser->get_user( $message->{from} )->{name},
            FromId  => $message->{from},
            Id      => $message->{id},
            IsAll   => $message->{is_all},
            Message => $comment,
            Subject => $message->{subject},
            Sent    => Zeromin2::Util::format_date($sent),
            SentTS  => $sent,
        }
    );

    return $zApp->return_value(0);
}

sub create {
    my ($zApp) = @_;
    $zApp->privilege() or return $zApp->return_value(1);

    $zApp->add_template_param( { Users => $zApp->user()->get_users() } );
    return $zApp->return_value(0);
}

sub send {
    my ($zApp) = @_;
    $zApp->check_csrf() or return $zApp->return_value(1);
    $zApp->privilege()  or return $zApp->return_value(1);

    my $zUser    = $zApp->user();
    my $iRequest = $zApp->request();
    my $send_to  = $iRequest->param('to') || '*';
    if ( $send_to eq '*' ) {
        $zApp->privilege('can_view_zeromin_log')
            or return $zApp->return_value(1);
    }
    else {
        defined $zUser->get_user($send_to)->{id}
            or return $zApp->return_value(2);
    }

    my $subject     = $iRequest->param('subject');
    my $message     = $iRequest->param('message');
    my $subject_len = length $subject || return $zApp->return_value(3);
    my $message_len = length $message || return $zApp->return_value(5);
    $subject_len > 256  and return $zApp->return_value(4);
    $message_len > 4096 and return $zApp->return_value(6);

    my $zMessage = Zeromin::Message->new( $zApp->kernel() );
    $zMessage->set_sender( $zUser->get_current_user()->{id} );
    $zMessage->send( $send_to, $subject, $message );

    return $zApp->return_value(0);
}

sub remove {
    my ($zApp) = @_;
    $zApp->check_csrf() or return $zApp->return_value(1);
    $zApp->privilege()  or return $zApp->return_value(1);

    my @param = $zApp->request()->param('id');
    scalar @param or return $zApp->return_value(2);

    my $zUser    = $zApp->user();
    my $zMessage = Zeromin::Message->new( $zApp->kernel() );
    $zMessage->set_sender( $zApp->user()->get_current_user()->{id} );

    my $status = {};
    for my $id (@param) {
        my ( $message_id, $from_id ) = split '\.', $id, 2;
        $message_id = Img0ch::Kernel::intval($message_id) || next;
        my $data = $zMessage->get( $message_id, $from_id );
        ( $data->{is_all} and !$zUser->can_view_zeromin_log() ) and next;
        if ( $zMessage->remove( $message_id, $from_id ) ) {
            $zApp->logger(
                1,
                'REMOVED MESSAGE: [%d] %s',
                [ $message_id, $data->{subject} ]
            );
            $status->{$message_id} = 1;
        }
        else {
            $zApp->logger( 0, 'TRIED REMOVING MESSAGE: %d', [$message_id] );
            $status->{$message_id} = 0;
        }
    }

    return $zApp->return_value(0);
}

1;
__END__
