<?php

namespace model;

use DAL\{ArticleGateway, Connection, FluxGateway};
use Exception;
use metier\Article;
use metier\Flux;

class ArticleModel
{
    /**
     * @throws Exception
     */
    public static function getArticles() : array
    {
        $gwArticle = new ArticleGateway(new Connection('mysql:host=londres.uca.local;dbname=dbrorossetto','rorossetto','tpphp'));
        $tabArticle = array();
        $res = $gwArticle->getAllArticles();
        foreach($res as $row){
            $tabArticle[] = new Article($row['id'], $row['title'],$row['datePub'],$row['description'],$row['guid'],$row['link'],$row['mediaContent'],$row['provenance'] );
        }
        return $tabArticle;
    }

    /**
     * @throws Exception
     */
    public function findArticleByFlux(Flux $flux){
        $con = new Connection('mysql:host=londres.uca.local;dbname=dbrorossetto','rorossetto','tpphp');
        $gwArticle = new ArticleGateway($con);
        $dicoFluxArticle = array();
        $tabArticle = array();
        $res = $gwArticle->findArticleByFlux($flux->getId());

        foreach ($res as $row){
            $tabArticle[] = new Article($row['id'], $row['title'],$row['datePub'],$row['description'],$row['guid'],$row['link'],$row['mediaContent'],$row['provenance'] );
        }
        $dicoFluxArticle[] = [$flux,$tabArticle];
        return $dicoFluxArticle;
    }

    public function findAllArticleByAllFlux(){
        $con = new Connection('mysql:host=londres.uca.local;dbname=dbrorossetto','rorossetto','tpphp');
        $gwFlux = new FluxGateway($con);
        $tabFluxArticle = array();
        $res = $gwFlux->findAllFlux();

        foreach ($res as $row) {
            $flux = new Flux((int)($row['id']),$row['flux']);
            $tabFluxArticle[] = $this->findArticleByFluxAsStr($flux);
        }
        return $tabFluxArticle;
    }

    public function findArticleByFluxAsStr(Flux $flux){
        $con = new Connection('mysql:host=londres.uca.local;dbname=dbrorossetto','rorossetto','tpphp');
        $gwArticle = new ArticleGateway($con);
        $tabArticle = array();
        $res = $gwArticle->findArticleByFlux($flux->getId());

        foreach ($res as $row){
            $article = new Article($row['id'], $row['title'],$row['datePub'],$row['description'],$row['guid'],$row['link'],$row['mediaContent'],$row['provenance'] );
            $tabArticle[] = (string)$article;
        }
        $dicoFluxArticle = [$flux,$tabArticle];
        return $dicoFluxArticle;
    }

    public static function removeArticleIdFlux(int $idFlux)
    {
        $gwArticle = new ArticleGateway(new Connection('mysql:host=londres.uca.local;dbname=dbrorossetto','rorossetto','tpphp'));
        $gwArticle->removeAllArticleFromFlux($idFlux);
    }
}