<?php

namespace AppBundle\Entity;

use AppBundle\Enum\MediaType;
use Cocur\Slugify\Slugify;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Table(name="Media")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\MediaRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Media
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $title
     *
     * @ORM\Column(name="title", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $title = "";

    /**
     * @var string $linkLabel
     *
     * @ORM\Column(name="linkLabel", type="string", length=255, nullable=true)
     */
    private $linkLabel = "";

    /**
     * @var string $description
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    private $description;

    /**
     * @var string $path
     *
     * @ORM\Column(name="path", type="string", length=255, nullable=true)
     */
    private $path;

    /**
     * @var string $type
     *
     * @ORM\Column(name="type", type="string", length=255, nullable=false)
     */
    private $type;

    /**
     * @var integer $position
     *
     * @ORM\Column(name="position", type="integer", nullable=true)
     */
    private $position = 0;

    /**
     * @var boolean $is_active
     *
     * @ORM\Column(name="is_active", type="boolean", nullable=true)
     */
    private $is_active = true;

    /**
     * @var \DateTime $created
     *
     * @ORM\Column(name="created", type="date", nullable=true)
     */
    private $created;

    /**
     * @var string $pagePerso
     *
     * @ORM\Column(name="pagePerso", type="text", nullable=true)
     */
    private $pagePerso;

    /**
     * @var string $opeItdlcEmail
     *
     * @ORM\Column(name="opeItdlcEmail", type="text", nullable=true)
     */
    private $opeItdlcEmail;

    /**
     * @var ArrayCollection
     * @ORM\ManyToMany(targetEntity="Menu", inversedBy="media")
     * @ORM\JoinTable(name="MediaMenu")
     */
    private $menu;

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="MenuMedia", mappedBy="media", cascade={"remove"})
     */
    protected $menumedias;


    /**
     * Constructor
     */
    public function __construct()
    {
        $this->menu = new ArrayCollection();
        $this->menumedias = new ArrayCollection();
    }
    
    public function __toString()
    {
        return $this->title;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Media
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get linkLabel
     *
     * @return string
     */
    public function getLinkLabel()
    {
        return $this->linkLabel;
    }

    /**
     * Set linkLabel
     *
     * @param string $linkLabel
     * @return Media
     */
    public function setLinkLabel($linkLabel)
    {
        $this->linkLabel = $linkLabel;

        return $this;
    }

    

    /**
     * Set description
     *
     * @param string $description
     * @return Media
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set position
     *
     * @param int $position
     * @return Media
     */
    public function setPosition($position)
    {
        $this->position = $position;

        return $this;
    }

    /**
     * Get position
     *
     * @return integer
     */
    public function getPosition()
    {
        return $this->position;
    }

    /**
     * Set is_active
     *
     * @param bool $isActive
     * @return Media
     */
    public function setIsActive($isActive)
    {
        $this->is_active = $isActive;

        return $this;
    }

    /**
     * Get is_active
     *
     * @return boolean
     */
    public function getIsActive()
    {
        return $this->is_active;
    }

    /**
     * Set path
     *
     * @param string $path
     * @return Media
     */
    public function setPath($path)
    {
        $this->path = $path;

        return $this;
    }

    /**
     * Get path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Set type
     *
     * @param string $type
     * @return Media
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Get menu
     *
     * @return ArrayCollection
     */
    public function getMenu()
    {
        return $this->menu;
    }


    /*** UPLOAD PICTURE ***/

    private $tempPicture;
    private $tempPdf;

    /**
     * @Assert\Image(
     *      maxWidth = 1728,
     *      maxWidthMessage = "Lʼimage ne doit pas dépasser 1728 pixels de large",
     *      maxHeight = 972,
     *      maxHeightMessage = "Lʼimage ne doit pas dépasser 972 pixels de haut",
     *      maxSizeMessage = "Lʼimage ne doit pas dépasser 5Mb.",
     *      maxSize = "6000000",
     *      mimeTypes = {"image/jpg", "image/jpeg", "image/gif", "image/png"},
     *      mimeTypesMessage = "Les images doivent être au format JPG, GIF ou PNG."
     * )
     */
    private $filePicture;

    /**
     * @Assert\File(
     *      maxSizeMessage = "Le document ne doit pas dépasser 5Mb.",
     *      maxSize = "6000000",
     *      mimeTypes = {"application/pdf", "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
     *      mimeTypesMessage = "L'extension du document doit être .pdf, .ppt ou pptx"
     * )
     */
    private $filePdf;

    /**
     * Sets file.
     *
     * @param UploadedFile $filePicture
     */
    public function setFilePicture(UploadedFile $filePicture = null)
    {
        $this->filePicture = $filePicture;

        // check if we have an old image path
        if (is_file($this->getAbsolutePicture())) {
            // store the old name to delete after the update
            $this->tempPicture = $this->getAbsolutePicture();
        } else {
            $this->path = 'initial';
        }
    }

    /**
     * Sets file.
     *
     * @param UploadedFile $filePdf
     */
    public function setFilePdf(UploadedFile $filePdf = null)
    {
        $this->filePdf = $filePdf;

        // check if we have an old image path
        if (is_file($this->getAbsolutePdf())) {
            // store the old name to delete after the update
            $this->tempPdf = $this->getAbsolutePdf();
        } else {
            $this->path = 'initial';
        }
    }

    /**
     * Get file.
     *
     * @return UploadedFile
     */
    public function getFilePicture()
    {
        return $this->filePicture;
    }

    /**
     * Get file.
     *
     * @return UploadedFile
     */
    public function getFilePdf()
    {
        return $this->filePdf;
    }

    public function getAbsolutePath()
    {
        return null === $this->path
            ? null
            : $this->getUploadRootDir() . DIRECTORY_SEPARATOR . $this->path;
    }

    /**
     * @deprecated Use getAbsolutePath() instead.
     * @return string
     */
    public function getAbsolutePicture()
    {
        return null === $this->path
            ? null
            : $this->getUploadRootDirPicture().'/'.$this->path;
    }

    /**
     * @deprecated Use getAbsolutePath() instead.
     * @return string
     */
    public function getAbsolutePdf()
    {
        return null === $this->path
            ? null
            : $this->getUploadRootDirPdf().'/'.$this->path;
    }

    public function getWebPath()
    {
        return null === $this->path
            ? null
            : $this->getUploadDir() . DIRECTORY_SEPARATOR . $this->path;
    }

    /**
     * @deprecated Use getWebPath() instead.
     * @return string
     */
    public function getWebPathPicture()
    {
        return null === $this->path
            ? null
            : $this->getUploadDirPicture().'/'.$this->path;
    }

    /**
     * @deprecated Use getWebPath() instead.
     * @return string
     */
    public function getWebPathPdf()
    {
        return null === $this->path
            ? null
            : $this->getUploadDirPdf().'/'.$this->path;
    }

    public function getWebPicture()
    {
        return $this->getWebPathPicture();
    }

    public function getWebPdf()
    {
        return $this->getWebPathPdf();
    }

    /**
     * Absolute directory path where uploaded
     * documents should be saved.
     * @return string
     */
    protected function getUploadRootDir()
    {
        return __DIR__
            . DIRECTORY_SEPARATOR
            . join(DIRECTORY_SEPARATOR, ['..', '..', '..', 'web'])
            . DIRECTORY_SEPARATOR
            . $this->getUploadDir()
        ;
    }

    /**
     * @deprecated Use getUploadRootDir() instead.
     * @return string
     */
    protected function getUploadRootDirPicture()
    {
        return __DIR__.'/../../../web/'.$this->getUploadDirPicture();
    }

    /**
     * @deprecated Use getUploadRootDir() instead.
     * @return string
     */
    protected function getUploadRootDirPdf()
    {
        return __DIR__.'/../../../web/'.$this->getUploadDirPdf();
    }

    /**
     * @return string
     */
    public function getUploadDir()
    {
        return join(DIRECTORY_SEPARATOR, ['uploads', 'media', $this->type]);
    }

    /**
     * @deprecated Use getUploadDir() instead.
     * @return string
     */
    protected function getUploadDirPicture()
    {
        return 'uploads/media/picture';
    }

    /**
     * @deprecated Use getUploadDir() instead.
     * @return string
     */
    protected function getUploadDirPdf()
    {
        return 'uploads/media/pdf';
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        $uniqueIdentifier = sha1(uniqid(mt_rand(), true));
        $slugify = new Slugify();

        if (null !== $this->getFilePicture()) {
            $filenameWithoutExtension = substr($this->getFilePicture()->getClientOriginalName(), 0, -1 * (strlen($this->getFilePicture()->getClientOriginalExtension()) + 1));

            $this->path = $uniqueIdentifier . '-' . $slugify->slugify($filenameWithoutExtension) . '.' . $this->getFilePicture()->getClientOriginalExtension();
        }

        if (null !== $this->getFilePdf()) {
            $filenameWithoutExtension = substr($this->getFilePdf()->getClientOriginalName(), 0, -1 * (strlen($this->getFilePdf()->getClientOriginalExtension()) + 1));

            $this->path = $uniqueIdentifier . '-' . $slugify->slugify($filenameWithoutExtension) . '.' . $this->getFilePdf()->getClientOriginalExtension();
        }
    }

    public function uploadFilePicture()
    {
        if (null === $this->getFilePicture()) {
            return;
        }

        if (isset($this->tempPicture)) {
            $this->tempPicture = null;

            if (is_file($this->tempPicture)) {
                unlink($this->tempPicture);
            }
        }

        $this->getFilePicture()->move(
            $this->getUploadRootDirPicture(),
            $this->path
        );

        $this->setFilePicture(null);
    }

    public function uploadFilePdf()
    {
        if (null === $this->getFilePdf()) {
            return;
        }

        if (isset($this->tempPdf)) {
            $this->tempPdf = null;

            if (is_file($this->tempPdf)) {
                unlink($this->tempPdf);
            }
        }

        $this->getFilePdf()->move(
            $this->getUploadRootDirPdf(),
            $this->path
        );

        $this->setFilePdf(null);
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        $this->uploadFilePicture();
        $this->uploadFilePdf();
    }

    /**
     * @ORM\PreRemove()
     */
    public function storeFilenameForRemove()
    {
        if (MediaType::PICTURE == $this->getType()) {
            $this->tempPicture = $this->getAbsolutePicture();
        } elseif (MediaType::PDF == $this->getType()){
            $this->tempPdf = $this->getAbsolutePdf();
        }
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        if (isset($this->tempPicture) && is_file($this->tempPicture)) {
            unlink($this->tempPicture);
        }

        if (isset($this->tempPdf) && is_file($this->tempPdf)) {
            unlink($this->tempPdf);
        }
    }

    /**
     * Set pagePerso
     *
     * @param array $pagePerso
     * @return Media
     */
    public function setPagePerso($pagePerso)
    {
        $this->pagePerso = implode('|', $pagePerso);

        return $this;
    }

    /**
     * Get pagePerso
     *
     * @return string
     */
    public function getPagePerso()
    {
        return explode('|', $this->pagePerso);
    }


    /**
     * Set opeItdlcEmail
     *
     * @param array $opeItdlcEmail
     * @return Media
     */
    public function setOpeItdlcEmail($opeItdlcEmail)
    {
        $this->opeItdlcEmail = implode('|', $opeItdlcEmail);

        return $this;
    }

    /**
     * Get opeItdlcEmail
     *
     * @return string
     */
    public function getOpeItdlcEmail()
    {
        return explode('|', $this->opeItdlcEmail);
    }

    


    /**
     * Add menu
     *
     * @param Menu $menu
     * @return Media
     */
    public function addMenu(Menu $menu)
    {
        $this->menu[] = $menu;

        return $this;
    }

    /**
     * Remove menu
     *
     * @param Menu $menu
     */
    public function removeMenu(Menu $menu)
    {
        $this->menu->removeElement($menu);
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Media
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * @ORM\PrePersist
     */
    public function setCreatedValue()
    {
        $this->created = new \DateTime();
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Add MenuMedia
     * @param MenuMedia $menumedia
     * @return Media
     */
    public function addMenuMedia(MenuMedia $menumedia)
    {
        $this->menumedias[] = $menumedia;

        return $this;
    }

    /**
     * Remove MenuMedia
     * @param MenuMedia $menumedia
     */
    public function removeMenuMedia(MenuMedia $menumedia)
    {
        $this->menumedias->removeElement($menumedia);
    }

    /**
     * Get menumedias
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMenuMedias()
    {
        return $this->menumedias;
    }
}
