#/*
# *  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: Thumbnail.pm 1230 2007-10-01 13:40:05Z hikarin $
#

package Img0ch::Plugin::Upload::Thumbnail;

use strict;
use Img0ch::Upload::Thumbnail qw();

sub new {
    my ( $iClass, $iBBS, $key, $called ) = @_;
    $called eq 'iterator' or return;

    bless {
        __kernel  => $iBBS->get_kernel(),
        __setting => $iBBS->get_setting_instance(),
        __upload  => $iBBS->get_upload_instance($key),
    }, $iClass;
}

sub create {
    my ($iApp) = @_;
    my $iUpload = $iApp->upload();
    -r $iUpload->get_uploaded_file_path() or return 0;

    my $iKernel  = $iApp->kernel();
    my $iSetting = $iApp->setting();
    _process( $iKernel, $iSetting, $iUpload );
    return 1;
}

*batch = \&repair;

sub repair {
    my ( $iObject, $key ) = @_;
    my $iKernel  = $iObject->{__kernel};
    my $iSetting = $iObject->{__setting};
    my $iUpload  = $iObject->{__upload};

    $iUpload->set_key($key);
    for my $file_path ( @{ $iUpload->traverse() } ) {
        $file_path =~ m{/\d+\.(?:gif|jpg|png)\z}xms or next;
        _process( $iKernel, $iSetting, $iUpload, $file_path );
    }
    return 1;
}

sub _process {
    my ( $iKernel, $iSetting, $iUpload, $path ) = @_;
    my $max_width  = $iSetting->get_int('BBS_IMG_THUMBNAIL_X');
    my $max_height = $iSetting->get_int('BBS_IMG_THUMBNAIL_X');

    $path ||= $iUpload->get_uploaded_file_path();
    my $dest = $path;

    my ( $resno, $ext ) = $path =~ m{/(\d+)\.(\w+)\z}xms;
    my ( $width, $height ) = $iUpload->get_dimensions($path);
    my ( $scaled_width, $scaled_height )
        = $iUpload->scale( $width, $height, $max_width, $max_height );
    $dest =~ s{/(\d+\..+)\z}{/t$1}xms;

    my $fh = $iKernel->get_write_file_handle($dest);
    Img0ch::Upload::Thumbnail->create(
        $iKernel,
        {   ext    => $ext,
            fh     => $fh,
            height => $scaled_height,
            path   => $path,
            width  => $scaled_width,
        },
    );
    close $fh or $iKernel->throw_io_exception($dest);

    $iUpload->set_thumbnail_size( $resno, $scaled_width, $scaled_height );
    $iUpload->save();

    return 1;
}

1;
__END__
