<?php
namespace Model;
use Entity\SourceEntity;
use Gateway\SourceGateway;

class SourceModel
{

    private sourceGateway $gateway;

    public function __construct(SourceGateway $gateway)
    {
        $this -> gateway = $gateway;
    }

    public function createSource(int $id_source, string $title, string $date) : bool
    {
        $q = new SourceEntity($id_source , $title, $date);

        return $this -> gateway -> create($q);
    }

    public function getSourceById(int $id_source) : ?SourceEntity
    {
        $res = $this -> gateway -> findById($id_source);
        
        if ($res)
            return new sourceEntity(
                $res[0]["id_source"],
                $res[0]["title"],
                $res[0]["date"]
            );
        return null;
    }

    public function getSourceByTitle(string $title) : array
    {
        $res = $this->gateway->findByTitle($title);
        foreach ($res as $sources) {
            $src[] = new sourceEntity(
                    $sources["id_source"],
                    $sources["title"],
                    $sources["date"]
                );
        }
        return $src;
    }

    public function getSourceByDate(string $date) : array
    {
        $res = $this->gateway->findByDate($date);
        foreach ($res as $sources) {
            $src[] = new sourceEntity(
                    $sources["id_source"],
                    $sources["title"],
                    $sources["date"]
                );
        }
        return $src;
    }

    public function getSources() : array
    {
        return $this -> gateway -> findAll();
    }

    public function deleteSource(int $id_source) : bool
    {
        return $this -> gateway -> delete($id_source);
    }

    public function updateSource(int $id_source, string $title, string $date) : bool
    {
        $q = $this -> getSourceById($id_source);

        if ($q){
            $q -> setTitle($title);
            $q -> setDate($date);
            return $this -> gateway -> update($q);
        }
        return false;
    }

}

