<?php

set_time_limit(0);

setUpClassAutoLoader();
$logLevel=Log::LOGLEVEL_INFO; //may be overridden by argument
$barcode='';

for($i=1;$i<count($argv);$i++){
    $arg=$argv[$i];
    if(preg_match('/^-b.+$/',$arg)){
        $importMode="barcode";
        $barcode=substr($arg, 2);
    } else if(preg_match('/^-l[1-4]$/',$arg)){
        $logLevel=(int)substr($arg, 2);
    }
}

if(''==$barcode){
    echo "\nThumbnail generator\n\n";
    echo "It seems that CrystalTrak fails to generate image thumbnails in some circumstances.\n";
    echo "IceBear will not import images where either image or thumbnail is absent.\n";
    echo "This script generates any missing thumbnails for the specified plate barcode.\n\n";
    echo "\nUsage: php makeThumbnails.php -bBARCODE\n";
    exit;
}

try {
    Log::init($logLevel);

    Log::write(Log::LOGLEVEL_INFO, 'Thumbnail generator started');

    if (extension_loaded('gd') && function_exists('gd_info')) {
        Log::write(Log::LOGLEVEL_DEBUG, 'GD image library is installed.');
    } else {
        throw new ServerException("GD image library not installed. Cannot generate thumbnails.");
    }

    Log::write(Log::LOGLEVEL_DEBUG, 'Attempting to get LIMS DB connection... ');
    database::connect();
    Log::write(Log::LOGLEVEL_DEBUG, '...got LIMS DB connection');
    Log::write(Log::LOGLEVEL_DEBUG, 'Attempting to get LIMS session... ');
    try {
        session::init(new DummySession());
    } catch (BadRequestException $e) {
        Log::write(Log::LOGLEVEL_ERROR, '...session::init threw BadRequestException');
        exit();
    } catch (NotFoundException $e) {
        Log::write(Log::LOGLEVEL_ERROR, '...session::init threw NotFoundException');
        exit();
    } catch (ServerException $e) {
        Log::write(Log::LOGLEVEL_ERROR, '...session::init threw ServerException');
        exit();
    }
    session::set('isAdmin', true);
    Log::write(Log::LOGLEVEL_DEBUG, '...got LIMS session');
    generateThumbnails($barcode);

} catch (ServerException $e){
    session::set('isAdmin', false);
    echo 'Exception thrown, and further exception thrown when logging error. Cannot continue.';
    exit();
}

Log::info("Thumbnail generator finished");

function generateThumbnails($barcode){
    $imageStore=config::get('rigaku_imagepath');
    $thumbStore=config::get('rigaku_thumbpath');
    if(empty($thumbStore) ||  empty($imageStore)){
        throw new Exception('Config items rigaku_imagepath and rigaku_thumbpath must both be defined');
    }
    $imageStore=rtrim($imageStore,'/').'/'.$barcode.'/';
    $thumbStore=rtrim($thumbStore,'/').'/'.$barcode.'/';
    Log::info("Images directory: $imageStore");
    Log::info("Thumbs directory: $thumbStore");
    $inspections=dir($imageStore);
    while($inspectionNumber=$inspections->read()){
        Log::debug("Found in image store: $inspectionNumber");
        if(!is_numeric($inspectionNumber)) {
            continue;
        }
        Log::debug("Will check/generate thumbnails from: $inspectionNumber");

        $source=$imageStore.$inspectionNumber.'/';
        $destination=$thumbStore.$inspectionNumber.'/';
        if(!file_exists($destination)){
            Log::debug('Creating inspection thumbnails directory '.$destination);
            if(!mkdir($destination)){
                throw new ServerException('Could not create thumbnails directory '.$destination);
            }
        } else {
            Log::debug('Inspection thumbnails directory '.$destination.' exists');
        }

        $destination=$thumbStore.$inspectionNumber.'/Thumbnails/';
        if(!file_exists($destination)){
            Log::debug('Creating inspection thumbnails directory '.$destination);
            if(!mkdir($destination)){
                throw new ServerException('Could not create thumbnails directory '.$destination);
            }
        } else {
            Log::debug('Inspection thumbnails directory '.$destination.' exists');
        }

        $destination=$thumbStore.$inspectionNumber.'/Thumbnails/160/';
        if(!file_exists($destination)){
            Log::info('Creating inspection thumbnails directory '.$destination);
            if(!mkdir($destination)){
                throw new ServerException('Could not create thumbnails directory '.$destination);
            }
        } else {
            Log::info('Inspection thumbnails directory '.$destination.' exists');
        }

        $images=dir($source);
        while($image=$images->read()){
            if(!str_contains($image, '.jpg')){
                Log::debug("$image does not contain .jpg, ignoring");
                continue;
            }

            $source=$imageStore.$inspectionNumber.'/'.$image;
            $destination=$thumbStore.$inspectionNumber.'/Thumbnails/160/'.str_replace('.jpg', '_160.jpg', $image);
            Log::debug('Image: '.$source);
            Log::debug('Thumb: '.$destination);
            if(file_exists($destination)){
                Log::debug('Thumbnail exists');
                continue;
            } else {
                Log::debug('Thumbnail does not exist');
            }

            list($imageWidth,$imageHeight)=getimagesize($source);
            if(!$imageWidth){
                Log::warning("$image is corrupt (could not get height/width), ignoring");
                continue;
            }
            Log::info("Found $imageWidth x $imageHeight image");

            $thumbWidth=160;
            $thumbHeight=(int)(($imageHeight/$imageWidth)*$thumbWidth);
            Log::debug("Thumbnail will be $thumbWidth x $thumbHeight");

            $gdImage=imagecreatefromjpeg($source);
            $gdThumb=imagecreatetruecolor($thumbWidth, $thumbHeight);
            imagecopyresampled($gdThumb, $gdImage,0,0,0,0,$thumbWidth,$thumbHeight,$imageWidth,$imageHeight);
            imagejpeg($gdThumb,$destination,100);

        }


    }
}

function setUpClassAutoLoader(){
    spl_autoload_register(function($className){
        $paths=array(
            '../classes/',
            '../classes/core/',
            '../classes/core/exception/',
            '../classes/core/authentication/',
            '../classes/core/interface/',
            '../classes/model/',
        );
        foreach($paths as $path){
            if(file_exists($path.$className.'.class.php')){
                include_once($path.$className.'.class.php');
            }
        }
    });
}
