#/*
# *  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 610 2007-05-09 14:49:15Z 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 $freezed  = ( stat( $iBBS->path('img') ) )[2] & 07777 == 0700;
    my $bbs      = $iBBS->get_name();
    my $lightbox = $iConfig->get('UploadImageLinkRelative') || 'lightbox[%s]';
    my $url      = $iBBS->url('img');
    my $ufm
        = Img0ch::Request->get_app_uri2($iConfig)
        . '/img0ch-ufm.cgi/'
        . $bbs . '/';

    bless {
        __bbs              => $bbs,
        __base_file_url    => $url,
        __cache_key        => $key,
        __is_freezed       => $freezed,
        __i0_upload        => $iUpload,
        __link_relative    => $lightbox,
        __removed_mark     => $iUpload->removed_mark(),
        __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,
        __use_fileseek     => $iConfig->get('UseFileSeek'),
        __use_picto        => $iConfig->get('UsePicto'),
    }, $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 $base_file_url = join '/', $iObject->{__base_file_url}, $key;
    my $file_name     = join '.', $resno, $extension;
    my $file_url      = join '/', $base_file_url, $file_name;

    if ( $iObject->{__is_freezed} ) {
        $$text =~ s{\A.*?$file_url.*?\(.+?\)<br(\s/)?>}
            {<b>[UNDOWNLOADABLE]</b><br$1>}xms;
    }
    elsif ( $hash eq $iObject->{__removed_mark} ) {
        $$text =~ s{\A.*?$file_url.*?\(.+?\)<br(\s/)?>}
            {<b>[NOT_FOUND]</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   = "${base_file_url}/t${file_name}";
            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 ) = @_;
    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 ( $iObject->{__is_freezed} ) {
        $$text =~ s{\A.*?$file_url.*?\((.+?)\)<br>}
            {<b>[UNDOWNLOADABLE]</b><br>}xms;
    }
    elsif ( $hash eq $iObject->{__removed_mark} ) {
        $$text =~ s{\A.*?$file_url.*?\((.+?)\)<br>}
            {<b>[NOT_FOUND]</b><br>}xms;
    }
    else {
        my ( $x, $y ) = ( 0, 0 );
        my $is_image = (
                   $extension eq 'jpg'
                or $extension eq 'gif'
                or $extension eq 'png'
        );
        my $use_fseek = $iObject->{__use_fileseek};
        my $format;
        if ( $iObject->{__use_picto} and $is_image ) {
            my $url = $file_url;
            $url =~ s{\Ahttp://}{}xms;
            $format = join( '',
                '<a href="http://pic.to/',
                $url, '">[IMAGE:', uc($extension), '(PIC.TO)]</a>' );
        }
        elsif (
            $use_fseek
            and (  $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 ( $use_fseek and $is_image ) {
            $format = join( '',
                '<a href="http://fileseek.net/getimg.html?',
                $file_url, '">[IMAGE:', 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__
