<?php
namespace Gateway;
use Enum\TypeSourceEnum;
use Entity\SourceEntity;
use PDO;

class SourceGateway extends Gateway{

    public function create(sourceEntity $s) : bool
    {
        $query = "
            INSERT INTO Source
            VALUES(:id, :title, :date)
        ";

        return $this -> co -> executeQuery($query, [
            "id" => array($s->getIdSource(), PDO::PARAM_INT),
            "title" => array($s->getTitle(), PDO::PARAM_STR),
            "date" => array($s->getDate(), PDO::PARAM_STR),
            #"type" => array($s->getType(), PDO::PARAM_STR)
        ]);
    }

    public function findById(int $id) : array
    {
        $query = "SELECT * FROM Source WHERE id_source = :id";

        $this -> co -> executeQuery($query, array("id" => array($id, PDO::PARAM_INT)));
        return $res = $this -> co -> getResults();
    }

    public function findByTitle(string $t) : array
    {
        $query = "SELECT * FROM Source WHERE title = :t";
        $this -> co -> executeQuery($query, ["t" => array($t, PDO::PARAM_STR)]);
        return $res = $this -> co -> getResults();
    }

    public function findByDate(string $d) : array
    {
        $query = "SELECT * FROM Source WHERE dates = :d";

        $this -> co -> executeQuery($query, ["d" => array($d, PDO::PARAM_STR)]);
        return $this -> co -> getResults();
    }
    
    /*
    public function findByType(TypeSourceEnum $type) : array
    {
        $query = "SELECT * FROM Source WHERE type = :t";

        $this -> co -> executeQuery($query, ["t" => array($type, PDO::PARAM_STR)]);
        return $this -> co -> getResults();
    }
    */

    public function findAll() : array
    {
        $query = "SELECT * FROM Source ORDER BY title ASC";
        $this -> co -> executeQuery($query);
        return $this -> co -> getResults();
    }

    public function delete(int $id) : bool
    {
        $query = "DELETE FROM Source WHERE id_source = :id_s";

        $this -> co -> executeQuery($query, ["id_s" => array($id, PDO::PARAM_INT)]);
    }

    public function update(sourceEntity $s) : bool
    {
        $query = "
            UPDATE Source 
            SET title = :t, date = :d 
            WHERE id_source = :id_s
        ";
        return $this->co->executeQuery($query, [
            "id_s" => array($s -> getIdSource(), PDO::PARAM_INT),
            "t" => array($s -> getTitle(), PDO::PARAM_STR),
            "d" => array($s -> getDate(), PDO::PARAM_STR)
        ]);
    }

    public function getLastId():int{
        $query = "SELECT id_source FROM Source;";
        $this -> co -> executeQuery($query);
        $res = $this -> co -> getResults();
        foreach($res as $r){
            $tab[] = $r["id_source"];
        }
        $id = 1;
        while(in_array($id,$tab))
        {
            $id=$id+1;
        }
        return $id;
    }

}
