<?php
namespace Cadoles\CoreBundle\EventListener;

use Doctrine\ORM\EntityManager;
use Oneup\UploaderBundle\Event\PostPersistEvent;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;

class uploadListener
{
    private $em;
    private $session;
    private $token;
    private $container;

    public function __construct(EntityManager $em, TokenStorageInterface $token_storage, Session $session, Container $container)
    {
        $this->em = $em;
        $this->session = $session;
        $this->token = $token_storage;
        $this->container = $container;
    }

    protected function getHeight($image) {
        $size = getimagesize($image);
        $height = $size[1];
        return $height;
    }

    // Cacul de la largeur
    protected function getWidth($image) {
        $size = getimagesize($image);
        $width = $size[0];
        return $width;
    }

    protected function resizeImage($image,$width,$height,$scale) {
        list($imagewidth, $imageheight, $imageType) = getimagesize($image);
        $imageType = image_type_to_mime_type($imageType);
        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
        switch($imageType) {
            case "image/gif":
                $source=imagecreatefromgif($image);
                break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                $source=imagecreatefromjpeg($image);
                break;
            case "image/png":
            case "image/x-png":
                $source=imagecreatefrompng($image);
                break;
        }

        $newImage = imagecreatetruecolor( $newImageWidth, $newImageHeight );
        imagealphablending( $newImage, false );
        imagesavealpha( $newImage, true );
        imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);

        switch($imageType) {
            case "image/gif":
                imagegif($newImage,$image);
                break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                imagejpeg($newImage,$image,90);
                break;
            case "image/png":
            case "image/x-png":
                imagepng($newImage,$image);
                break;
        }

        chmod($image, 0640);
        return $image;
    }

    public function onUpload(PostPersistEvent $event)
    {
        $type=$event->getType();
        switch($type) {
            case "avatar":
                $file=$event->getFile();
                $filename=$file->getFilename();
                $this->session->set('uploadavatar', $filename);
            break;
            case "file":
                $file=$event->getFile();
                $filename=$file->getFilename();
                $pathname=$file->getPath();

                // Déplacer le fichier dans la cible
                $request = $event->getRequest();
                $directory = $request->get('directory');
                $subdirectory = $request->get('subdirectory');
                if($subdirectory) $directory.="/".$subdirectory;
                
                $fs = new Filesystem();
                $fgexit=$fs->exists($pathname."/".$directory."/".$filename);
                $file->move($pathname."/".$directory, $filename);

                // Création d'un thumb dans le cas d'un fichier de type imapge
                if (in_array(strtolower($file->GetExtension()), array('jpg', 'jpeg', 'jpe', 'png', 'gif', 'bmp'))) {
                    $fs = new Filesystem();
                    $fs->copy($pathname."/".$directory."/".$filename,$pathname."/".$directory."/thumb/".$filename);
                    $max_width=300;
                    $width = $this->getWidth($pathname."/".$directory."/thumb/".$filename);
                    $height = $this->getHeight($pathname."/".$directory."/thumb/".$filename);                    
                    $scale = $max_width/$width;
                    $this->resizeImage($pathname."/".$directory."/thumb/".$filename,$width,$height,$scale);
                }


                if (in_array(strtolower($file->GetExtension()), array('pdf'))) {
                    $im = new \Imagick();
                    $im->setResolution(300, 300);
                    $im->readImage($pathname."/".$directory."/".$filename."[0]");
                    $im->setImageBackgroundColor('#ffffff');
                    $im = $im->flattenImages();
                    $im->setImageFormat('jpeg');
                    $fs->mkdir($pathname."/".$directory."/thumb");
                    $im->writeImage($pathname."/".$directory."/thumb/".$filename.".jpg");
                    $fs->rename($pathname."/".$directory."/thumb/".$filename.".jpg", $pathname."/".$directory."/thumb/".$filename);
                }

                if($fs->exists($pathname."/".$directory."/thumb/".$filename)) {
                    $fs->mkdir($pathname."/".$directory."/thumbmini");
                    $fs->copy($pathname."/".$directory."/thumb/".$filename,$pathname."/".$directory."/thumbmini/".$filename);
                    $max_width=60;
                    $width = $this->getWidth($pathname."/".$directory."/thumbmini/".$filename);
                    $height = $this->getHeight($pathname."/".$directory."/thumbmini/".$filename);                    
                    $scale = $max_width/$width;
                    $this->resizeImage($pathname."/".$directory."/thumbmini/".$filename,$width,$height,$scale);
                }

                if (strpos($directory, 'widget') === 0) {
                    $tmp=explode("-",$directory);
                    $widgetid=$tmp[1];
                    $widget=$this->em->getRepository("CadolesPortalBundle:Pagewidget")->find($widgetid);
                    if($widget) {
                        foreach($widget->getPage()->getGroups() as $group) {
                            if($group->getFgcanshare()) {
                                if($fgexit) $message="Modification fichier<br>".$filename;
                                else $message="Création fichier<br>".$filename;

                                $usergroup=$this->em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(["group"=>$group,"user"=>$this->token->getToken()->getUser()]);
                                if($usergroup) {
                                    $key=$usergroup->getKeyvalue();
                                    $websocket = $this->container->get('cadoles.websocket.pushmessage')->send($key,$this->token->getToken()->getUser()->getId(),$group->getId(),$message);
                                }
                            }
                        }
                    }
                }

                if (strpos($directory, 'projecttask') === 0) {
                    $tmp=explode("-",$directory);
                    $projecttaskid=$tmp[1];
                    $projecttask=$this->em->getRepository("CadolesPortalBundle:Projecttask")->find($projecttaskid);
                    if($projecttask) {
                        foreach($projecttask->getProject()->getGroups() as $group) {
                            if($group->getFgcanshare()) {
                                if($fgexit) $message="Modification fichier dans la tâche ".$projecttask->getName()."<br>".$filename;
                                else $message="Création fichier dans la tâche ".$projecttask->getName()."<br>".$filename;

                                $usergroup=$this->em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(["group"=>$group,"user"=>$this->token->getToken()->getUser()]);
                                if($usergroup) {
                                    $key=$usergroup->getKeyvalue();
                                    $websocket = $this->container->get('cadoles.websocket.pushmessage')->send($key,$this->token->getToken()->getUser()->getId(),$group->getId(),$message);
                                }
                            }
                        }
                    }
                }

                $response = $event->getResponse();
                $response['file'] = $filename;
            break;

            case "blogarticle":
                $file=$event->getFile();
                $filename=$file->getFilename();
                $pathname=$file->getPath();

                // Creation d'un thumb
                $fs = new Filesystem();
                $fs->copy($pathname."/".$filename,$pathname."/thumb-".$filename);
                $max_width=350;
                $width = $this->getWidth($pathname."/thumb-".$filename);
                $height = $this->getHeight($pathname."/thumb-".$filename);                    
                $scale = $max_width/$width;
                $this->resizeImage($pathname."/thumb-".$filename,$width,$height,$scale);

                $response = $event->getResponse();
                $response['file'] = $filename;                
            break;

            default:
                $file=$event->getFile();
                $filename=$file->getFilename();
                $response = $event->getResponse();
                $response['file'] = $filename;
            break;            
        }
    }
}
