#/*
# *  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: Image.pm 999 2007-08-29 12:57:14Z hikarin $
#

package Img0ch::Plugin::Rewrite::Image;

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

my $removeText = pack 'C*', 0x8d, 0xed, 0x8f, 0x9c;

sub new {
    my ( $iClass, $iBBS, $key ) = @_;
    my $iConfig  = $iBBS->get_kernel()->get_config();
    my $iSetting = Img0ch::Setting->new($iBBS);
    my $iUpload  = Img0ch::Upload->new( $iBBS, $key );
    my $bbs      = $iBBS->get_name();
    my $lightbox = $iConfig->get('UploadImageLinkRelative') || 'lightbox[%s]';
    my $ufm
        = Img0ch::Request->get_app_uri2($iConfig)
        . '/img0ch-ufm.cgi/'
        . $bbs . '/';
    my $resizer
        = Img0ch::Request->get_app_uri2($iConfig) . '/i.cgi/' . $bbs . '/';

    bless {
        __bbs              => $bbs,
        __cache_key        => $key,
        __i0_upload        => $iUpload,
        __link_relative    => $lightbox,
        __removed_mark     => $iUpload->removed_mark(),
        __resizer_url      => $resizer,
        __thumbnail_max    => $iSetting->get('BBS_IMG_THUMBNAIL_MAX'),
        __thumbnail_width  => $iSetting->get('BBS_IMG_THUMBNAIL_X'),
        __thumbnail_height => $iSetting->get('BBS_IMG_THUMBNAIL_Y'),
        __ufm              => $ufm,
    }, $iClass;
}

sub from_bbs {
    my ( $iObject, $key, $count, $resno, $text ) = @_;
    my $iUpload = $iObject->{__i0_upload};
    if ( $iObject->{__cache_key} ne $key ) {
        $iUpload->set_key($key);
        $iObject->{__cache_key} = $key;
        $iObject->{__i0_upload} = $iUpload;
    }

    my ( $extension, $width, $height, $hash ) = @{ $iUpload->get($resno) };
    $hash or return;

    my $max       = $iObject->{__thumbnail_max};
    my $file_name = join '.', $resno, $extension;
    my $file_url  = $iUpload->url( $resno, $extension );

    if ( $hash eq $iObject->{__removed_mark} ) {
        $$text =~ s{\A.*?$file_url.*?\(.+?\)<br(\s/)?>}
            {<b>[NOT_FOUND]</b><br$1>}xms;
    }
    elsif ( $iUpload->is_freezed($resno) ) {
        $$text =~ s{\A.*?$file_url.*?\(.+?\)<br(\s/)?>}
            {<b>[UNDOWNLOADABLE]</b><br$1>}xms;
    }
    elsif ( $iUpload->have_download_password($resno) ) {
        my $dlLink = '<b><a href="' . $iObject->{__ufm} . $key . '/';
        $dlLink .= $resno . '">[REQUIRE_DOWNLOAD_KEY]</a></b>';
        $$text =~ s{\A.*?$file_url.*?\((.+?)\)<br(\s/)?>}
            {$dlLink($1)<br$2>}xms;
    }
    else {
        my ( $x, $y ) = ( 0, 0 );
        my ( $scaled_width, $scaled_height );
        my $bbs_dir    = $iObject->{__bbs};
        my $relative   = $iObject->{__link_relative};
        my $max_width  = $iObject->{__thumbnail_width};
        my $max_height = $iObject->{__thumbnail_height};
        $relative =~ s/%s/${bbs_dir}_${key}/xms;

        my $removeLink = '<a href="' . $iObject->{__ufm} . $key . '/';
        $removeLink .= $resno . '" onclick="app.removeFile( this, ' . $key;
        $removeLink .= ', ' . $resno . ' ); return false">[';
        $removeLink .= $removeText . ']</a>';

        if ((       $extension ne 'jpg'
                and $extension ne 'gif'
                and $extension ne 'png'
            )
            or $resno <= $count - $max
            )
        {
            my $format = join( '',
                '<a href="',                $file_url,
                '" class="i0_image" id="f', $key,
                '_',                        $resno,
                '" rel="',                  $relative,
                '" title="',                $file_name,
                '"><b>[',                   $extension,
                ']</b></a>' );
            $$text =~ s{\A.+?\((.+?)\)<br(\s/)?>}
                {$format$removeLink($1)<br$2>}xms;
        }
        elsif (
            $iUpload->get_thumbnail_size(
                $resno, \$scaled_width, \$scaled_height
            )
            )
        {
            my $thumb_url   = $iUpload->url( "t${resno}", $extension );
            my $alternative = "${file_name} - ${width}x${height}";
            my $format      = join( '',
                '<a href="',                             $file_url,
                '" class="i0_image i0_thumbnail" id="f', $bbs_dir,
                '_',                                     $key,
                '_',                                     $resno,
                '" rel="',                               $relative,
                '" title="',                             $alternative,
                '"><img src="',                          $thumb_url,
                '" alt="',                               $alternative,
                '" width="',                             $scaled_width,
                '" height="',                            $scaled_height,
                '" id="i',                               $bbs_dir,
                '_',                                     $key,
                '_',                                     $resno,
                '" class="image" /></a>' );
            $$text =~ s{\A.+?\((.+?)\)<br(\s/)?>}
                {$format($1)$removeLink<br$2>}xms;
            $$text .= '<br class="clear" />';
        }
        elsif ( $width and $height ) {
            ( $scaled_width, $scaled_height )
                = $iUpload->scale( $width, $height, $max_width, $max_height );
            my $alternative = "${file_name} - ${width}x${height}";
            my $format      = join( '',
                '<a href="',                $file_url,
                '" class="i0_image" id="f', $bbs_dir,
                '_',                        $key,
                '_',                        $resno,
                '" rel="',                  $relative,
                '" title="',                $alternative,
                '"><img src="',             $file_url,
                '" alt="',                  $alternative,
                '" width="',                $scaled_width,
                '" height="',               $scaled_height,
                '" id="i',                  $bbs_dir,
                '_',                        $key,
                '_',                        $resno,
                '" class="image" /></a>' );
            $$text =~ s{\A.+?\((.+?)\)<br(\s/)?>}
                {$format($1)$removeLink<br$2>}xms;
            $$text .= '<br class="clear" />';
        }
        else {
            my $format = join( '',
                '<a href="',               $file_url,
                '" class="i0_file" id="f', $bbs_dir,
                '_',                       $key,
                '_',                       $resno,
                '">',                      '<b>[',
                $extension,                ']</b></a>' );
            $$text =~ s{\A.+?\((.+?)\)<br(\s/)?>}
                {$format$removeLink($1)<br$2>}xms;
        }
    }
    return;
}

*from_read = \&from_bbs;

sub from_mobile {
    my ( $iObject, $key, $count, $resno, $text, $param ) = @_;
    my $iUpload = $iObject->{__i0_upload};
    if ( $iObject->{__cache_key} ne $key ) {
        $iUpload->set_key($key);
        $iObject->{__cache_key} = $key;
        $iObject->{__i0_upload} = $iUpload;
    }

    my ( $extension, $width, $height, $hash ) = @{ $iUpload->get($resno) };
    $extension or return;
    my $file_url = join '/', $iUpload->url( $resno, $extension );

    if ( $hash eq $iObject->{__removed_mark} ) {
        $$text =~ s{\A.*?$file_url.*?\((.+?)\)<br>}
            {<b>[NOT_FOUND]</b><br>}xms;
    }
    elsif ( $iUpload->is_freezed($resno) ) {
        $$text =~ s{\A.*?$file_url.*?\((.+?)\)<br>}
            {<b>[UNDOWNLOADABLE]</b><br>}xms;
    }
    else {
        my ( $x, $y ) = ( 0, 0 );
        my $is_image = (
                   $extension eq 'jpg'
                or $extension eq 'gif'
                or $extension eq 'png'
        );
        my $format;
        if ($is_image) {
            my $thumbnail_img_tag;
            my ( $scaled_width, $scaled_height ) = ( 0, 0 );
            if (    $param->{thumbnail}
                and $resno > $count - $iObject->{__thumbnail_max}
                and $iUpload->get_thumbnail_size(
                    $resno, \$scaled_width, \$scaled_height
                )
                )
            {
                my $thumb_url = $iUpload->url( "t${resno}", $extension );
                $thumbnail_img_tag = join '', '<img src=', $thumb_url,
                    ' width=', $scaled_width, ' height=', $scaled_height,
                    '><br>';
            }
            my $url = $file_url;
            $url =~ s{\Ahttp://}{}xms;
            $format = join( '',
                $thumbnail_img_tag,
                '[<a href="',
                $iObject->{__resizer_url},
                $key,
                '/',
                $resno,
                '">IMAGE:',
                uc($extension),
                '</a>(<a href="',
                $file_url,
                '">DIRECT</a>:',
                $width,
                'x',
                $height,
                ')/<a href="http://pic.to/',
                $url,
                '">PIC.TO</a>/<a href="http://fileseek.net/getimg.html?',
                $file_url,
                '">FILESEEK.NET</a>]',
            );
        }
        elsif ($extension eq 'mpg'
            or $extension eq 'avi'
            or $extension eq 'wmv'
            or $extension eq 'wma'
            or $extension eq 'mp3'
            or $extension eq 'wav' )
        {
            $format = join( '',
                '<a href="http://fileseek.net/',
                'getmovie.html?', $file_url, '">[MOVIE:', uc($extension),
                '(FILESEEK.NET)]</a>' );
        }
        elsif ( $width and $height ) {
            $format = join( '',
                '<a href="',    $file_url, '">[IMAGE:',
                uc($extension), '(',       $width,
                'x',            $height,   ')]</a>' );
        }
        else {
            $format = join( '',
                '<a href="', $file_url, '">[FILE:', $extension, ']</a>' );
        }
        $$text =~ s{\A.+?\((.+?)\)<br\s?/?>}{${format}($1)<br>}xms;
    }
    return;
}

1;
__END__
