<?php 
 
namespace App\Controller; 
 
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; 
use Symfony\Component\Routing\Annotation\Route; 
 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpFoundation\Request as Request; 
use Symfony\Component\HttpFoundation\JsonResponse; 
 
use Symfony\Component\HttpFoundation\File\File; 
 
use Doctrine\ORM\EntityManagerInterface; 
 
use App\Service\UserService; 
use App\Service\ImageService; 
 
use App\Entity\Image; 
 
use App\Entity\Product; 
 
class ImageController extends AbstractController 
{ 
    private $messageServ; 
    private $userServ; 
    private $entityMana; 
    private $imageServ; 
 
    public function __construct(ImageService $imageServ, UserService $user, EntityManagerInterface $em){ 
        $this->imageServ = $imageServ; 
        $this->userServ = $user; 
        $this->entityMana = $em; 
    } 
 
 
    /** 
     * @Route("/image/{id}", name="getImage") 
     */ 
    public function getImage(Image $image){ 
        header('Content-Type:'.$image->getMime()); 
        header('Content-Length: ' . $image->getWeight()); 
        return new Response(readfile($image->getImage())); 
    } 
 
    /** 
     * @Route("/nutritionFact/{id}",  
     *      name="getNutritionFactImage", 
     * ) 
     */ 
    public function getNutritionFactImage(Product $product, UserService $user){ 
 
        $userId = $user->getId(); 
        $filename= $this->getParameter('ProductImagesDir').$userId.'/images/'.$product->getNutritionFact(); 
        $image = new File($filename); 
 
        header('Content-Type:'.$image->getMimeType()); 
        header('Content-Length: ' . $image->getWeight()); 
        return new Response(readfile($filename)); 
    } 
 
    /** 
     * @Route("/image/resize/{id}/{height}/{width}", name="getImageResized") 
     */ 
    public function getImageResized(Image $image=NULL, $height, $width){ 
        if($image){ 
            if(!$this->checkCache($image, $height, $width, 'resize')){ 
                if(file_exists($image->getImage())) 
                    $img = new \Gumlet\ImageResize($image->getImage()); 
                else 
                    $img = new \Gumlet\ImageResize('assets/shared/images/defaultAvatar.jpg'); 
            }else 
                return new Response(); 
 
            $img->resize($width, $height); 
            $filename = $image->getImage().'_resize_'.$height.'x'.$width; 
            $img->save($filename, IMAGETYPE_JPEG); 
 
            return new Response($img->output()); 
        }else{ 
            $img = new \Gumlet\ImageResize('assets/frontend/images/noProductPicture.jpg'); 
            return new Response($img->output()); 
        } 
    } 
 
    /** 
     * @Route("/image/thumbnail/{id}/{height}/{width}", name="getImageAsThumb") 
     */ 
    public function getImageAsThumbnail(Image $image=NULL, $height, $width){ 
        if($image){ 
            if(!$this->checkCache($image, $height, $width, 'thumbnail')){ 
                if(file_exists($image->getImage())) 
                    $img = new \Gumlet\ImageResize($image->getImage()); 
                else 
                    $img = new \Gumlet\ImageResize('assets/shared/images/defaultAvatar.jpg'); 
            }else 
                return new Response(); 
 
            $img->resizeToBestfit($width, $height); 
            $filename = $image->getImage().'_thumbnail_'.$height.'x'.$width; 
            $img->save($filename, IMAGETYPE_JPEG); 
 
            return new Response($img->output()); 
        }else{ 
            $img = new \Gumlet\ImageResize('assets/frontend/images/noProductPicture.jpg'); 
            return new Response(); 
        } 
    } 
 
    /** 
     * @Route( 
     *      "/image/product/{id}/crop/{height}/{width}", 
     *      options = { "expose" = true }, 
     *      name="getProductImageAsCroppedThumb" 
     *  ) 
     */ 
    public function getProductImageAsCroppedThumb(Product $product, $height, $width){ 
        return $this->getImageAsCroppedThumbnail($product->getMainImage(), $height, $width); 
    } 
 
 
    /** 
     * @Route("/image/crop/{id}/{height}/{width}", name="getImageAsCroppedThumb") 
     */ 
    public function getImageAsCroppedThumbnail(Image $image=NULL, $height, $width){ 
        $save = true; 
 
        if($image && file_exists($image->getImage())){ 
            if(!$this->checkCache($image, $height, $width, 'cropThumb')){ 
                if(file_exists($image->getImage())) 
                    $img = new \Gumlet\ImageResize($image->getImage()); 
                else{ 
                   $img = new \Gumlet\ImageResize('assets/shared/images/defaultAvatar.jpg'); 
                   $save = false; 
                } 
            }else{ 
                return new Response(); 
        } 
        }else{ 
            $img = new \Gumlet\ImageResize('assets/frontend/images/noProductPicture.jpg'); 
            $save = false; 
        } 
 
        //$img->crop($height, $width); 
        $img->crop($width, $height); 
 
        if($image){ 
            $filename = $image->getImage().'_cropThumb_'.$height.'x'.$width; 
            if($save) 
                $img->save($filename, IMAGETYPE_JPEG); 
        } 
 
        return new Response($img->output()); 
    } 
 
    /** 
     * @Route("/image/fixedHeight/{id}/{height}", name="getImageAsFixedHeight") 
     */ 
    public function getImageAsFixedHeight(Image $image, $height){ 
        if(file_exists($image->getImage())){ 
            if(!$this->checkCache($image, $height, 'X', 'fixedHeight')) 
                $img = new \Gumlet\ImageResize($image->getImage()); 
            else 
                return new Response(); 
        }else 
            $img = new \Gumlet\ImageResize('assets/shared/images/defaultAvatar.jpg'); 
 
        $img->resizeToHeight($height); 
        $filename = $image->getImage().'_fixedHeight_'.$height.'xX'; 
        $img->save($filename, IMAGETYPE_JPEG); 
 
        return new Response($img->output()); 
    } 
 
    /** 
     * @Route("/image/fixedWidth/{id}/{width}", name="getImageAsFixedWidth") 
     */ 
    public function getImageAsFixedWidth(Image $image, $width){ 
        if(file_exists($image->getImage())){ 
            if(!$this->checkCache($image, 'X', $width, 'fixedWidth')) 
                $img = new \Gumlet\ImageResize($image->getImage()); 
            else 
                return new Response(); 
        }else 
            $img = new \Gumlet\ImageResize('assets/shared/images/defaultAvatar.jpg'); 
 
        $img->resizeToWidth($width); 
        $filename = $image->getImage().'_fixedWidth_Xx'.$width; 
        $img->save($filename, IMAGETYPE_JPEG); 
 
        return new Response($img->output()); 
    } 
 
    /* 
     * Check if a cached version exists 
     */ 
    public function checkCache($image, $height='', $width='', $suffix=''){ 
        if(!$image) 
            return false; 
 
        $filename = $image->getImage().'_'.$suffix.'_'.$height.'x'.$width; 
 
        //Check if file exists if so we assure there is no update since last crop 
        if(file_exists($filename)){ 
            $fileDate = new \DateTime(); 
            $fileDate->setTimestamp(filemtime($filename)); 
            if($fileDate > $image->getLastUpdated()){ 
                $file = new File($filename); 
                header('Content-Type:'.$file->getMimeType()); 
                header('Content-Length: ' . filesize($filename)); 
                return new Response(readfile($filename)); 
            }else 
                return false; 
        } 
 
        return false; 
    } 
 
    /** 
     * @Route("/API/getImage/{action}/{opt}",  
     *      options = { "expose" = true }, 
     *      name="getImageByAction" 
     *  ) 
     * 
     *  NOTE This is for Data gathering only 
     *  Use setImageByActionFromAPI if you need to set a Iamge from API 
     */ 
    public function getImageByActionFromAPI($action, $opt=false, Request $request){ 
        $action = strtolower($action); 
        $return = array(); 
 
        switch($action){ 
        case 'test': 
            break; 
        }; 
        $response = new JsonResponse(); 
        $response->setData($return); 
 
        return $response; 
    } 
 
    /** 
     * @Route("/API/setImage/{action}/{opt}",  
     *      options = { "expose" = true }, 
     *      name="setImageByAction" 
     *  ) 
     * 
     *  NOTE This is for Data Setting only 
     *  Use getImageByActionFromAPI if you need to gather a Image from API 
     */ 
    public function setImageByActionFromAPI($action, $opt=false, Request $request){ 
        $action = strtolower($action); 
        $return = array(); 
 
        switch($action){ 
        case 'attributes': 
            $descs = json_decode($request->get('data')); 
            foreach($descs as $desc){ 
                $this->imageServ->updateDescription($desc->id, $desc->description); 
            } 
 
            $orders = json_decode($request->get('order')); 
            $cmtp = 1; 
            foreach($orders as $order){ 
                $this->imageServ->updateDisplayOrder($order, $cmtp); 
                $cmtp++; 
            } 
            $return['success'] = true; 
            break; 
 
        case 'delforproduct': 
            $product = $request->get('product'); 
            $id = $request->get('id'); 
            $return['success'] = $this->imageServ->deleteImage($id, false, $product); 
            break; 
 
        case 'delbyid': 
            $id = $request->get('id'); 
            $return['success'] = $this->imageServ->deleteImage($id); 
            break; 
        case 'blobupload': 
            $file = $request->files->get('picture'); 
            $image = $this->imageServ->saveUploadedFile($file, 'product'); 
            if($image){ 
                $return = array( 
                    "size" => $image->getWeight(), 
                    "url" => $this->generateURL('getImage', array('id' => $image->getId())), 
                    "thumbnailUrl" => $this->generateURL('getImageAsThumb', array('id' => $image->getId(), 'height' => '100', 'width' => '100')), 
                ); 
            } 
            break; 
 
        case 'profileimage': 
            $file = $request->files->get('picture'); 
            $image = $this->imageServ->saveUploadedFile($file, 'profile'); 
            if($image){ 
                $user = $this->userServ->getUser(); 
                $user->setProfileImage($image); 
                //Saving in the database 
                $this->entityMana->persist($user); 
                $this->entityMana->flush(); 
 
                $return = array( 
                    "id" => $image->getId(), 
                    "url" => $this->generateURL('getImageAsThumb', array('id' => $image->getId(), 'height' => '150', 'width' => '150')), 
                ); 
            } 
            break; 
 
 
        case 'updateimage': 
            $file = $request->files->get('picture'); 
            if(empty($file)){ 
                $file = $request->files->get('file'); 
            } 
 
            $id = $request->get('id'); 
            $image = $this->imageServ->updateImageFile($id, $file); 
            if($image){ 
                $ver = uniqid(); 
                $return = array( 
                    "weight" => $image->getWeight(), 
                    'size' => array($image->getWidth(), $image->getHeight()), 
                    "fullUrl" => $this->generateURL('getImage', array('id' => $image->getId())), 
                    "url" => $this->generateURL('getImageAsThumb', array('id' => $image->getId(), 'height' => '150', 'width' => '150')).'?'.$ver, 
                    "thumbnailUrl" => $this->generateURL('getImageAsThumb', array('id' => $image->getId(), 'height' => '100', 'width' => '100')).'?'.$ver, 
                ); 
            } 
            break; 
 
        case 'newimage': 
            $file = $request->files->get('file'); 
            $image = $this->imageServ->saveUploadedFile($file, 'newProduct'); 
            if($image){ 
                $return = array( 
                    "id" => $image->getId(), 
                    "weight" => $image->getWeight(), 
                    'size' => array($image->getWidth(), $image->getHeight()), 
                    "url" => $this->generateURL('getImageAsThumb', array('id' => $image->getId(), 'height' => '150', 'width' => '150')), 
                    "editUrl" => $this->generateURL('getImage', array('id' => $image->getId())), 
                    "fullUrl" => $this->generateURL('getImage', array('id' => $image->getId())), 
                    "thumbnailUrl" => $this->generateURL('getImageAsThumb', array('id' => $image->getId(), 'height' => '100', 'width' => '100')), 
                ); 
            } 
            break; 
        }; 
        $response = new JsonResponse(); 
        $response->setData($return); 
 
        return $response; 
    } 
}