<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Resize image on fly
 *
 * @author Igor Ratsun
 */
class image
{

    protected $sourcePath = 'assets/uploads/multimedia/images';
    protected $croppedPath = 'assets/uploads/cropped';
    protected $proccessLibrary = 'image_change'; // image_change or image_lib
    protected $watermark = array();
    protected $quality = 75;

    public function __construct($options = array())
    {
        // Set options
        if (is_array($options)) {
            foreach ($options as $option => $value) {
                $method = 'set' . ucfirst($option);
                if (method_exists($this, $method)) {
                    $this->{$method}($value);
                }
            }
        }
    }

    /**
     * Create image if needed and return full image path
     * @param string $file
     * @param int $width
     * @param int $height
     * @return string
     */
    public function getImage($file = '', $width = 0, $height = 0)
    {
        $srcFile = trim(str_replace(array('./', '../', $this->getSourcePath()), '', trim($file, '/')), '/');
        $srcFullPath = $this->getSourcePath() . '/' . $srcFile;
        if (empty($srcFile) || !file_exists($srcFullPath) || is_dir($srcFullPath)) {

            return '';
        }

        if (!empty($width) && !empty($height)) {
            $croppedFile = $this->createCrropedPath($srcFile, $width, $height)
                    . '/' . pathinfo($srcFile, PATHINFO_FILENAME)
                    . '.' . pathinfo($srcFile, PATHINFO_EXTENSION);
            if (!file_exists($croppedFile)) {
                $this->resize($srcFullPath, $croppedFile, $width, $height);
                $this->watermark($croppedFile);
            }
        } else {

            return $srcFullPath;
        }

        return base_url($croppedFile);
    }

    public function getSourcePath()
    {
        return $this->sourcePath;
    }

    public function getCroppedPath()
    {
        return $this->croppedPath;
    }

    public function getProccessLibrary()
    {
        return $this->proccessLibrary;
    }

    public function getWatermark()
    {
        return $this->watermark;
    }
    
    public function getQuality()
    {
        return $this->quality;
    }

    public function setSourcePath($sourcePath)
    {
        $this->sourcePath = $sourcePath;
        return $this;
    }

    public function setCroppedPath($croppedPath)
    {
        $this->croppedPath = $croppedPath;

        return $this;
    }

    public function setProccessLibrary($proccessLibrary)
    {
        $this->proccessLibrary = $proccessLibrary;

        return $this;
    }

    public function setWatermark($watermark = array())
    {
        $this->watermark = $watermark;

        return $this;
    }
    
    public function setQuality($quality = 75)
    {
        $this->quality = $quality;
        
        return $this;
    }

    protected function createCrropedPath($file = '', $width = 0, $height = 0)
    {
        $filePath = trim(pathinfo($file, PATHINFO_DIRNAME), '/');
        $path = trim($this->getCroppedPath(), '/') . '/' . $width . '_' . $height . ($filePath == '.' ? '' : '/' . $filePath);

        if (!file_exists($path)) {
            if (!mkdir($path, 0775, true)) {
                show_error('Can\'t create folder `' . $path . '`');
            }
        }

        return $path;
    }

    protected function resize($srcFile, $newFile, $width, $height)
    {
        $ci = & get_instance();

        if ($this->proccessLibrary == 'image_lib') {
            $config['image_library'] = 'gd2';
            $config['source_image'] = $srcFile;
            $config['new_image'] = $newFile;
            $config['maintain_ratio'] = false;
            $config['width'] = $width;
            $config['height'] = $height;
            $config['quality'] = $this->getQuality();
            $ci->load->library('image_lib');
            $ci->image_lib->initialize($config);

            return $ci->image_lib->resize();
        }

        if ($this->proccessLibrary == 'image_change') {
            copy($srcFile, $newFile);
            $ci->load->library('image_change', $newFile);
            $image = new Image_change($newFile);
            $image->resize($width, $height);

            return $image->save($newFile, $this->getQuality());
        }
    }

    protected function watermark($croppedFile)
    {
        if (!empty($this->watermark)) {
            $ci = & get_instance();
            $ci->load->library('image_lib');
            $config = $this->watermark;
            $config['source_image'] = $croppedFile;
            $ci->image_lib->initialize($config);
            $ci->image_lib->watermark();

            return true;
        }

        return false;
    }

}
