<?php

/**
 * Description of ImageController
 *
 * @author wolfgang
 */
class ImageController extends Zend_Controller_Action
{
    const IMAGE_URL = 'img/user/';
    const THUMB_DIR = 'thumb/';

    protected $imageUrl;
    protected $imagePath;

    protected $thumbUrl;
    protected $webRoot;

    public function init()
    {
        $this->imageUrl = $this->view->baseUrl(self::IMAGE_URL);
        $this->thumbUrl = $this->imageUrl . self::THUMB_DIR;
        $this->webRoot = getcwd();
        $this->imagePath = realpath($this->webRoot . DIRECTORY_SEPARATOR . self::IMAGE_URL);
        $this->thumbPath = $this->imagePath . DIRECTORY_SEPARATOR . self::THUMB_DIR;

    }

    public function listAction()
    {
        $list = array();

        if (!$this->getRequest()->isXmlHttpRequest()) {
            $this->_helper->json($list);
            return;
        }

        $dir = new DirectoryIterator($this->imagePath);
        foreach ($dir as $fileInfo) {
            if (in_array(pathinfo($fileInfo->getFilename(), PATHINFO_EXTENSION), array('jpg', 'gif', 'png'))) {
                $file['image'] = $this->imageUrl . $fileInfo->getFilename();
                $parts = pathinfo($fileInfo->getFilename());
                $file['title'] = ucfirst($parts['filename']);
                $file['thumb'] = $this->thumbUrl . $fileInfo->getFilename();
                $list[] = $file;
            }
        }
        $this->_helper->json($list);
    }

    public function uploadAction()
    {
        $upload = new Zend_File_Transfer_Adapter_Http();
        $filename = str_replace(array('/', '\\'), '', $upload->getFileName(null, false));
        $upload->addValidator('Extension', false, array('jpg', 'png', 'gif'))
            //->addValidator('IsImage', false)
            ->addFilter('rename', array('overwrite' => true,
                    'target' => $this->imagePath . DIRECTORY_SEPARATOR . $filename)
            );

        if ($upload->isValid()) {
            $upload->receive();

            chmod($upload->getFileName(), 0644);
            $this->resizeImage($upload->getFileName(), $this->thumbPath);

            $file['filelink'] = $this->imageUrl . $filename;
            $this->_helper->json($file);
            exit;
        } else {
            print_r($upload->getMessages());
            exit;
        }
    }

    function resizeImage($image, $thumbPath)
    {
        $resizedImage = $thumbPath . basename($image);
        if (!file_exists($resizedImage) && file_exists($image)) {
            $imageObj = new Varien_Image($image);
            $imageObj->constrainOnly(TRUE);
            $imageObj->keepAspectRatio(TRUE);
            $imageObj->keepFrame(FALSE);
            $imageObj->resize(100, 100);
            $imageObj->save($resizedImage);
        }
        return $resizedImage;
    }
}