<?php

namespace App\gateway;

use App\metier\Image;
use PDO;

class ImageGateway
{
    private Connection $con;

    /**
     * @param $con
     */
    public function __construct(Connection $con)
    {
        $this->con = $con;
    }


    public function insertImage(Image $img)
    {
        $query = "INSERT INTO Image (`nom`, `taille`, `type`, `blob`) VALUES ( :n, :t, :ty, :b)";
        $this->con->executeQuery($query, array(
            ':n' => array($img->getName(), PDO::PARAM_STR),
            ':t' => array($img->getTaille(), PDO::PARAM_STR),
            ':ty' => array($img->getType(), PDO::PARAM_STR),
            ':b' => array($img->getBlob(), PDO::PARAM_STR)
        ));
    }

    public function delete(int $id)
    {
        $query = 'DELETE FROM Image WHERE id=:i';
        $this->con->executeQuery($query, array(
            ':i' => array($id, PDO::PARAM_INT)
        ));
    }

    public function getFromId(int $id) : array
    {
        $query = 'SELECT * FROM Image WHERE id=:i';
        $this->con->executeQuery($query, array(
            ':i' => array($id, PDO::PARAM_INT)
        ));
        return $this->con->getResults();
    }

    public function getNewId() : int
    {
        $query = 'SELECT MAX(id) FROM Image';
        $this->con->executeQuery($query);
        $res = $this->con->getResults();
        if ($res[0]['MAX(id)'] === null) {
            return 1;
        }
        return intval($res[0]['MAX(id)'])+1;

    }

    public function obtenirToutesImages()
    {
        $query = 'SELECT * FROM Image';
        $this->con->executeQuery($query);
        $res = $this->con->getResults();
        $array = [];
        foreach ($res as $r) {
            $array[] = new Image($this->getNewId(),$r['nom'], $r['taille'], $r['type'], $r['blob']);
        }
        return $array;
    }
}

?>