<?php
/*
 * 2014 Vinum Master
 *
 * NOTICE OF LICENSE
 *
 *  @author Vinum Master <webmaster@vinummaster.com>
 *  @website http://www.vinummaster.com
 *  @copyright  2014 Vinum Master
 *  @license    Commercial
 *  @name module vm_advancedconfigurator
 *  @version  1.01 du 16/10/2014 // Only available for PS 1.6
 *  @file vm_advancedconfigurator.php
 *  @update  1.01 du 16/10/2014  
 *  International Registered Trademark & Property of Vinum Master
 */
class ImgGallery {

  private $thumbsize;	//Size of the image thumbnail
  private $elements;


  public function __construct(
  	$thumbsize=100, //Change this to match your thumbnail size
    	$elements=array()
  ){
    $this->thumbsize=$thumbsize;
    $this->elements = $elements;
  }
  
  
  //========================================//
  //=====> List the images to include <=====//
  //========================================//  
  public function getImageArray($url){
  	//Tell the class to look for images inside this folder
  	$path = $url.'/{*.jpg,*.gif,*.png}';
  	$imgarray=glob($path,GLOB_BRACE)?glob($path,GLOB_BRACE):array();
  	return $imgarray; //Return the found images
  }

  //=========================================//
  //=====> Add an image to the gallery <=====//
  //=========================================//  
  public function addImage($src){
  	$elements = $this->elements;
  	$elements[] = $src;
  	$this->elements = $elements;
  }
  
  //==========================================//
  //===> Add all the images from a folder <===//
  //==========================================//  
  public function loadImages($url){
  	$imgarray = $this->getImageArray($url);
  	if(!empty($imgarray)){foreach($imgarray as $img){ $this->addImage($img); }}
  }

  //=========================================//
  //==> Write the markup for the gallery <===//
  //=========================================//    
  public function display($url,$where,$what,$position){
    $markup='
    <div id="easyimgallery" style="top:'.$position.'px;">
      <ul>';
       $markup.='<li>
            <img src="'.__PS_BASE_URI__.'modules/vm_advancedconfigurator/views/img/backgrounds/cache/noitem.png" alt="noitem" data-rel="noitem" data-what="'.$what.'" onclick="whatimgurl(this);"/>
        </li>';
      if(!empty($this->elements)){foreach($this->elements as $img){
        $thumb=$this->getImageThumbnail($img,$url);
      //  $imgname=end(explode("/",$img));
        $imgname = Tools::substr(strrchr($img, '/'), 1);
        $markup.='<li>
          <img src="/'.$thumb.'" alt="'.$imgname.'" data-rel="'.$where.'" data-what="'.$what.'" onclick="whatimgurl(this);"/>
        </li>';
      }}
      $markup.='
      </ul>
    </div>';
    echo $markup;
    return $markup;
}

  //=========================================//
  //====> Easy call to set everything up <===//
  //=========================================//    
  public static function getPublicSide($url,$what,$position){
      //  $where=end(explode("/",$url));
         $where = Tools::substr(strrchr($url, '/'), 1);
  	$gallery = new ImgGallery();
  	$gallery->loadImages($url);
  	$gallery->display($url,$where,$what,$position);
  }
  
  //=========================================//
  //=====> Create the image thumbnail <======//
  //=========================================//    
  public function getImageThumbnail($src,$url){
	$size=$this->thumbsize;
	$imgSrc = $src;  
	
	//cached img
	$cachepath =$url.'/cache/'.$size.'x'.$size.''.str_replace("/","~",$imgSrc);	
        $thumbSize = $size;    
	
	if(file_exists($cachepath)){ return Tools::substr(__PS_BASE_URI__.'modules/vm_advancedconfigurator/'.$cachepath,1); } //If cached, return right away
	else {	//Create the thumbnail
		//getting the image dimensions   
		list($width, $height, $type) = getimagesize($imgSrc); 

		switch($type) {//saving the image into memory (for manipulation with GD Library)   
			case 1:
                        {
                            $myImage = imagecreatefromgif($imgSrc);
                            $background = imagecolorallocate($myImage, 0, 0, 0); 
                            imagecolortransparent($myImage, $background);
                             $thumb = imagecreatetruecolor($thumbSize, $thumbSize);    
                            break;
                        }
			case 2:
                        {
                            $myImage = imagecreatefromjpeg($imgSrc);
                             $thumb = imagecreatetruecolor($thumbSize, $thumbSize);  
                            break;
                        }
			case 3: 
                        {
                            $myImage = imagecreatefrompng($imgSrc);
                            	$thumb = imagecreatetruecolor($thumbSize, $thumbSize);    
	
                           imageAlphaBlending($thumb, false);
                            imageSaveAlpha($thumb, true);
                            break;
                        }
		}
		if($width>$size || $height>$size) {
			//setting the crop size   
			if($width > $height) $biggestSide = $width;    
			else $biggestSide = $height;    
			//The crop size will be half that of the largest side 
			$cropPercent = .5;    
			$cropWidth   = $biggestSide*$cropPercent;    
			$cropHeight  = $biggestSide*$cropPercent;    
		}
		else { $cropWidth   = $width; $cropHeight  = $height; }

		//getting the top left coordinate   
		$c1 = array("x"=>($width-$cropWidth)/2, "y"=>($height-$cropHeight)/2);   

		// Creating the thumbnail    
		imagecopyresampled($thumb, $myImage, 0, 0, $c1['x'], $c1['y'], $thumbSize, $thumbSize, $cropWidth, $cropHeight);

		//final output 
		$this->cachePicture($thumb,$cachepath);   
		imagedestroy($thumb);  
		return Tools::substr(__PS_BASE_URI__.'modules/vm_advancedconfigurator/'.$cachepath,1);
	}
  }

 

  //=============================================//
  //==> Save the dynamically created pictures <==//
  //=============================================//    
  public function cachePicture($im,$cachepath){
  	if(!is_dir(dirname($cachepath))){ mkdir(dirname($cachepath)); }
	if (function_exists("imagepng")) { imagepng($im,$cachepath); }
	elseif (function_exists("imagegif")) { imagegif($im,$cachepath); }
	elseif (function_exists("imagejpeg")) { imagejpeg($im,$cachepath, 0.5); }
	elseif (function_exists("imagewbmp")) { imagewbmp($im,$cachepath);} 
	else { die("Doh ! No graphical functions on this server ?"); }
	return $cachepath;  	
  }

  //=========================================================//
  //=> Used for debugging to see what the gallery contains <=//
  //=========================================================//    
  public function trace(){
  	highlight_string(print_r($this,true));
  }
  
}  

?>