<?php

namespace Repositories;

use Doctrine\ORM\EntityRepository;

/**
 * PictureRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PictureRepository extends EntityRepository {

    public function get() {
        $qb = $this->createQueryBuilder('p')
                ->select('p, r')
                ->leftJoin('p.resource', 'r');
        $picture = $qb->getQuery()->getArrayResult();
        return $picture[0];
    }
    
    public function update($thumb_id) {
        $alert = [
            'type' => 'success',
            'msg' => '<strong><i class="fa fa-check"></i></strong> La photo a été modifié avec succès.'
        ];
        $em = $this->getEntityManager();
        $cnx = $em->getConnection();
        $cnx->beginTransaction();
        try {
            $EntityTmp = $em->getRepository('Entities\Picture')->findAll();
            $entity = $EntityTmp[0];
            
            if ($thumb_id != null) {
                $thumb = $em->getRepository('Entities\Resource')->findOneBy(['id' => $thumb_id]);
                $entity->setResource($thumb);
            }
            $em->persist($entity);
            $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 dumpPicture() {
        $em = $this->getEntityManager();
        $picture = [
            [
                'resource' => [
                    [
                        'name' => 'profile_picture.jpg'
                    ]
                ]
            ]
        ];
        foreach ($picture as $p) {
            $entity = new \Entities\Picture();

            foreach ($p['resource'] as $thumb) {
                $thumbnail = new \Entities\Resource();
                $thumbnail->setName($thumb['name']);
                $em->persist($thumbnail);
                $entity->setResource($thumbnail);
            }

            $em->persist($entity);
            $em->flush();
        }
    }

}
