<?php

namespace Repositories;

use Doctrine\ORM\EntityRepository;

/**
 * GalerieRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class GalerieRepository extends EntityRepository
{
    public function get() {
        $qb = $this->createQueryBuilder('w');
        $qb->select('w, a, al, r, res')
                ->leftJoin('w.album', 'a')
                ->leftJoin('a.album_resources', 'al')
                ->leftJoin('w.image', 'res')
                ->leftJoin('al.resource', 'r')
                ->orderBy('w.pos', 'ASC')
        ;
        return $qb->getQuery()->getArrayResult();
    }
    
    public function getFront() {
        $qb = $this->createQueryBuilder('w');
        $qb->select('w, a, al, r, res')
                ->leftJoin('w.album', 'a')
                ->leftJoin('a.album_resources', 'al')
                ->leftJoin('w.image', 'res')
                ->leftJoin('al.resource', 'r')
                ->where('w.display = true')
                ->orderBy('w.pos', 'ASC')
        ;
        return $qb->getQuery()->getArrayResult();
    }

 
    public function getById($id) {
        $qb = $this->createQueryBuilder('w');
        $qb->select('w, a, al, r, res')
                ->leftJoin('w.album', 'a')
                ->leftJoin('a.album_resources', 'al')
                ->leftJoin('al.resource', 'r')
                ->leftJoin('w.image', 'res')
                ->where(sprintf("w.id = '%s'", $id));
        return $qb->getQuery()->getArrayResult();
    }
    
    public function switchState($id){
        $qb = $this->createQueryBuilder('r');
        $state = $this->getState($id);
        $qb->update();
                if ($state[0]["display"])
                    $qb->set('r.display', 'false');
                else
                    $qb->set('r.display', 'true');
                
                 $qb->where('r.id=:id')
                 ->setParameter('id', $id)
                 ->getQuery()
                 ->execute();
                if($state[0]["display"])
                    return 0;
                else
                    return 1;
    }
    
    public function getState($id)
    {        
        $qb = $this->createQueryBuilder('r');
        $qb->select('r.display')                
                ->where('r.id=:id')
                ->setParameter('id', $id);
        return $qb->getQuery()->getResult();
    }

    public function add($galerie, $files, $thumb_id) {
        $alert = [
            'type' => 'success',
            'msg' => '<strong><i class="fa fa-check"></i></strong> ' . $galerie['title'] . ' a été ajoutée avec succès.'
        ];
        $em = $this->getEntityManager();
        $cnx = $em->getConnection();
        $cnx->beginTransaction();
        try {
            $entity = new \Entities\Galerie();
            $album = new \Entities\Album();
            $entity->setTitle($galerie['title']);
            $entity->setDescription($galerie['description']);
            $entity->setDate($galerie['date']);
            $entity->setDisplay($galerie['display']);
            $entity->setPos($galerie['pos']);
            $entity->setAddress($galerie['address']);
            $entity->setAlbum($album);
            $album->setTitle($galerie['title']);

            $thumb = $em->getRepository('Entities\Resource')->findOneBy(['id' => $thumb_id]);
            $entity->setImage($thumb);


            // link images to the album
            foreach ($files as $file_id) {
                if ($file_id != null) {
                    $resource = $em->getRepository('Entities\Resource')->findOneBy(['id' => $file_id]);
                    $album_resource = new \Entities\AlbumResource();
                    $album_resource->setResource($resource);
                    $album_resource->setAlbum($album);
                    $em->persist($album_resource);
                }
            }
            $em->persist($entity);
            $em->persist($album);
            $em->flush();
            $cnx->commit();
        } catch (Exception $ex) {
            $cnx->rollback();
            $alert = [
                'type' => 'danger',
                'msg' => '<strong><i class="fa fa-warning"></i></strong> Une erreur interne est survenus, veuillez recommancer plutard.'
            ];
        }
        return $alert;
    }

   
    public function update($id, $galerie, $files, $thumb_id) {
        $alert = [
            'type' => 'success',
            'msg' => '<strong><i class="fa fa-check"></i></strong>  ' . $galerie['title'] . ' a été modifiée avec succès.'
        ];
        
        $em = $this->getEntityManager();
        $cnx = $em->getConnection();
        $cnx->beginTransaction();
        try {
            $entity = $em->getRepository('Entities\Galerie')->find($id);
            $entity->setTitle($galerie['title']);
            $entity->setDescription($galerie['description']);
            $entity->setDate($galerie['date']);
            $entity->setDisplay($galerie['display']);
            $entity->setPos($galerie['pos']);
            $entity->setAddress($galerie['address']);

            if ($thumb_id != null) {
                $image = $em->getRepository('Entities\Resource')->findOneBy(['id' => $entity->getImage()]);
                $em->remove($image);
                unlink($entity->getImage()->getFullPath());
                $thumb = $em->getRepository('Entities\Resource')->findOneBy(['id' => $thumb_id]);
                $entity->setImage($thumb);
            }
           
            foreach ($files as $file_id) {
                if ($file_id != null) {
                    $resource = $em->getRepository('Entities\Resource')->findOneBy(['id' => (int) $file_id]);
                    $album_resource = new \Entities\AlbumResource();
                    $album_resource->setResource($resource);
                    $album_resource->setAlbum($entity->getAlbum());
                    $em->persist($album_resource);
                }
            }
            $em->flush();
            $cnx->commit();
        } catch (Exception $ex) {
            $cnx->rollback();
            $alert = [
                'type' => 'danger',
                'msg' => '<strong><i class="fa fa-warning"></i></strong> Une erreur interne est survenus, veuillez recommancer plutard.'
            ];
        }
        return $alert;
    }
    
    public function delete($id, $name) {
        $alert = [
            'type' => 'success',
            'msg' => '<strong><i class="fa fa-check"></i></strong> L\'album ' . $name . ' a été supprimé avec succès.'
        ];
        $em = $this->getEntityManager();
        $cnx = $em->getConnection();
        $cnx->beginTransaction();
        try {
            $em->remove($this->find($id));
            $em->flush();
            $cnx->commit();
        } catch (Exception $ex) {
            $cnx->rollback();
            $alert = [
                'type' => 'danger',
                'msg' => '<strong><i class="fa fa-warning"></i></strong> Une erreur interne est survenus, veuillez recommancer plutard.'
            ];
        }
        return $alert;
    }
}