<?php
/*
 * Crop Adjust
 *
 * @package
 * @author Rihards Silins
 * @copyright MTC Media 22/09/2014
 * @version 1
 * @access public
 *
 * Class that does various image file manipulations in
 * order to re-crop cms2 iamages defined in $image_folders['cms_images'].
 *
 * TODO: Once in core - replace SITE_PATH with relative $path
 */
Class CropAdjust
{
	/**
	 * Generate new unique filename.
	 *
	 * @param string current_filename
	 * @return string new_filename
	 */
	static function refreshImageUniqueName( $current_filename ) {

		// get original filename by removing the prepend time()
		preg_match("/^[0-9]{10}(.+\.[^\.]+)$/", $current_filename, $matches);
		// prepend a new time()
		$new_filename = time().$matches[1];

		return $new_filename;
	}

	/**
	 * Raname cms2 image (all size cuts) to new name
	 *
	 * @param array $image_folders['cms_images']
	 * @param string original_filename
	 * @param string new_filename
	 * @return bool success
	 */
	static function renameAllImageSizes( $sizes, $original_filename, $new_filename ) {

		foreach ($sizes as $key => $size) {

			$directory_path = SITE_PATH."/".$size['path']."/";

			if ( is_dir($directory_path) && file_exists($directory_path.$original_filename) ) {

				rename($directory_path.$original_filename, $directory_path.$new_filename);

			}

		}

		return true;
	}

	/**
	 * Crop image according to params
	 *
	 * @param string image_filename
	 * @param string source_path
	 * @param array cms_images_target_size_params
	 * @param string jcrop_width
	 * @param string jcrop_height
	 * @param string jcrop_x_offset
	 * @param string jcrop_y_offset
	 * @return bool success
	 */
	static function recrop( $filename, $source_path, $size_params, $jcrop_width, $jcrop_height, $jcrop_x_offset, $jcrop_y_offset ) {

		$result = copy(
			SITE_PATH."/".$source_path."/".$filename,
			SITE_PATH."/".$size_params['path']."/".$filename
		);

		if ( $result === false ) {
			return false;
		}

		image_crop(
			$size_params['path'], //source
			$filename, //dest
			$jcrop_width,
			$jcrop_height,
			$jcrop_x_offset,
			$jcrop_y_offset
		);

	    the_image_resize(
	    	$size_params['width'],
	    	$size_params['height'],
	    	$size_params['path'], //source
	    	$filename //dest
	    );

	    return true;

	}

}