<?php

/**
 * Description of ImageHelper
 *
 * @author Mohammed Osman  <osmancode@gmail.com>
 */
class ImageHelper {

    public static function resize(&$model, $attribute, $old_value = false, $fill_space = false) {
        $model->$attribute = CUploadedFile::getInstance($model, $attribute);
		//var_dump($model->$attribute);
        if ($model->$attribute != NULL) {
            // validate
            if ($model->validate(null, false)) {
                //extension
                $ext = $model->$attribute->getExtensionName();
                // unique name
                $uniqid = uniqid();
                // new file name
                $new_image_name = "{$uniqid}.{$ext}";
                // upload directory
                $upload_directory = Yii::app()->params['uploadDir'] . get_class($model);
                if (!is_dir($upload_directory)) {
                    CFileHelper::createDirectory($upload_directory);
                }
                // new image location
                $new_image_path = "{$upload_directory}/{$new_image_name}";

                if ($model->$attribute->saveAs($new_image_path)) {
                    $model->$attribute = $new_image_name;
                    if ($fill_space) {
                        foreach ($sizes as $dir => $size) {
                            $img = Yii::app()->image->load($upload_directory . '/' . $new_image_name);
                            self::thumbnail_box($img, $newWidth, $newHeight);
                        }
                    } else {
                        self::resizeImage($model->getThumbnailSizes(), $upload_directory, $new_image_name, true);
                    }
                }
                if ($old_value) {
                    self::removeOld($model, $old_value);
                }
            }
        } else {
            if ($old_value) {
                $model->$attribute = $old_value;
            }
        }
    }

    public static function resizeImage($sizes, $upload_directory, $image, $same_ratio = false) {
        /* @var $component Image */
        // load orignal image to resize

        $upload_directory = rtrim($upload_directory, '/');

        $component = Yii::app()->image->load($upload_directory . '/' . $image);

        foreach ($sizes as $dir => $size) {
            // upload directory
            $upload_directory = "{$upload_directory}/{$dir}";
            if (!is_dir($upload_directory)) {
                CFileHelper::createDirectory($upload_directory);
            }
            // new image location
            $new_image_path = "{$upload_directory}/{$image}";

            if ($size[0] === 0) {
                $size[0] = round(($component->width * $size[1]) / $component->height);
            }
            if ($size[1] === 0) {
                $size[1] = round(($component->width * $size[0]) / $component->height);
            }
            if ($same_ratio) {
                $image_mode = 'land';
                //set the new image size  with the same ratio
                //1- check if the image is portriate or landscal
                if ($component->height > $component->width)
                    $image_mode = 'por';
                if ($image_mode == 'por') {
                    //find the percentage 
                    $pers = $component->height / $size[1];
                    //inorder to not change smaller image
                    if ($pers > 1) {
                        $size[0] = $component->width / $pers;
                        $size[1] = $component->height / $pers;
                    }
                } else {
                    //find the percentage 
                    $pers = $component->width / $size[0];
                    //inorder to not change smaller image
                    if ($pers > 1) {
                        $size[0] = $component->width / $pers;
                        $size[1] = $component->height / $pers;
                    }
                }
            }
            $component->resize($size[0], $size[1], Image::NONE);
            $component->save($new_image_path);
        }
    }

    public static function removeOld($model, $old_image) {
        $upload_directory = Yii::app()->params['uploadDir'] . get_class($model);

        $image = "{$upload_directory}/{$old_image}";
        if (is_file($image)) {
            @unlink($image);
        }

        foreach ($model->getThumbnailSizes() as $dir => $size) {
            // upload directory
            $upload_directory = "{$upload_directory}/{$dir}";
            $image = "{$upload_directory}/{$old_image}";
            if (is_file($image)) {
                @unlink($image);
            }
        }
    }

    public static function remove(&$model, $attribute) {
        $upload_directory = Yii::app()->params['uploadDir'] . get_class($model);

        $image = "{$upload_directory}/{$model->$attribute}";
        if (is_file($image)) {
            @unlink($image);
        }
        foreach ($model->getThumbnailSizes() as $dir => $size) {
            // upload directory
            $upload_directory = "{$upload_directory}/{$dir}";
            $image = "{$upload_directory}/{$model->$attribute}";
            if (is_file($image)) {
                @unlink($image);
            }
        }
    }

    //my update ()
    public static function thumbnailBox($image, $path, $box_w, $box_h, $hex) {
        $extension = $image->getExtensionName();
        $img = self::helperLoad($image, $path);
        if ($img != null) {
            $rgb = self::hex2rgb($hex);
            //create the image
            $new = imagecreatetruecolor($box_w, $box_h);
            if ($new === false) {

                return null;
            }

            $fill = imagecolorallocate($new, $rgb[0], $rgb[1], $rgb[2]);
            imagefill($new, 0, 0, $fill);

            //compute resize ratio
            $hratio = $box_h / imagesy($img);
            $wratio = $box_w / imagesx($img);
            $ratio = min($hratio, $wratio);

            if ($ratio > 1.0)
                $ratio = 1.0;

            //compute sizes
            $sy = floor(imagesy($img) * $ratio);
            $sx = floor(imagesx($img) * $ratio);
            // image
            $start_y = floor(($box_h - $sy) / 2);
            $start_x = floor(($box_w - $sx) / 2);
//        echo $img->width;
            if (!imagecopyresampled($new, $img, $start_x, $start_y, 0, 0, $sx, $sy, imagesx($img), imagesy($img))) {
                //copy failed
                imagedestroy($new);
                return null;
            } else {
                imagedestroy($img);
            }
            //copy successful

            return array('img' => $new, 'ext' => $extension);
        }
    }

    public static function helperLoad($image, $loadPath) {
        //get image Extension
        $ext = $image->getExtensionName();
        switch ($ext) {
            case 'jpg':
            case 'jpeg':
                // Check PHP supports this file type
                if (imagetypes() & IMG_JPG) {
                    $img = imagecreatefromjpeg($loadPath);
                }
                break;

            case 'gif':
                // Check PHP supports this file type
                if (imagetypes() & IMG_GIF) {
                    $img = imagecreatefromgif($loadPath);
                }
                break;

            case 'png':
                $invertScaleQuality = 9 - round(($imageQuality / 100) * 9);

                // Check PHP supports this file type
                if (imagetypes() & IMG_PNG) {
                    $img = imagecreatefrompng($loadPath);
                }
                break;
        }
        return $img;
    }

    public static function helperSave($image, $savePath, $imageQuality = 100) {
        $ext = $image['ext'];
        $img = $image['img'];
        $is_save = false;
        switch ($ext) {
            case 'jpg':
            case 'jpeg':
                // Check PHP supports this file type
                if (imagetypes() & IMG_JPG) {
                    if (imagejpeg($img, $savePath, $imageQuality))
                        $is_save = true;
                }
                break;

            case 'gif':
                // Check PHP supports this file type
                if (imagetypes() & IMG_GIF) {
                    if (imagegif($img, $savePath)) {
                        $is_save = true;
                    }
                }
                break;

            case 'png':
                $invertScaleQuality = 9 - round(($imageQuality / 100) * 9);

                // Check PHP supports this file type
                if (imagetypes() & IMG_PNG) {
                    if (imagepng($img, $savePath, $invertScaleQuality)) {
                        $is_save = true;
                    }
                }
                break;
        }
        return $is_save;
    }

//covert color from hex 2 rgb
    public static function hex2rgb($hex) {
        $hex = str_replace("#", "", $hex);

        if (strlen($hex) == 3) {
            $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
            $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
            $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
        } else {
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
        }
        $rgb = array($r, $g, $b);
        //return implode(",", $rgb); // returns the rgb values separated by commas
        return $rgb; // returns an array with the rgb values
    }

}
