<?php

/*
 * PuzzleApp
 * Webemyos
 * Jérôme Oliva
 * GNU Licence
 */

namespace Apps\Blog\Helper;

use Core\Entity\Entity\Argument;
use Core\Utility\Format\Format;
use Apps\Blog\Entity\BlogArticle;
use Apps\Blog\Entity\BlogCategory;
use Apps\Blog\Widget\BlogCategoryForm\BlogCategoryForm;

class CategoryHelper {

    /**
     * Sauvagarde une catégorie
     */
    public static function Save($core, $name, $description, $blogId, $categoryId) {
        $category = new BlogCategory($core);

        if ($categoryId != "") {
            $category->GetById($categoryId);
        }

        $category->Name->Value = $name;
        $category->Code->Value = Format::ReplaceForUrl($name);
        $category->Description->Value = $description;

        if ($blogId != "") {
            $category->BlogId->Value = $blogId;
        }

        $category->Save();
    }

    /**
     * Retourne les catégories d'un blog
     * @param type $core
     * @param type $blogId
     */
    public static function GetByBlog($core, $blogId) {
        $category = new BlogCategory($core);
        $category->AddArgument(new Argument("Apps\Blog\Entity\BlogCategory", "BlogId", EQUAL, $blogId));

        return $category->GetByArg();
    }

    /**
     * Obtient le nombre d'article correspondant
     */
    public static function GetNumberArticle($core, $categoryId) {
        $article = new BlogArticle($core);
        $article->AddArgument(new Argument("Apps\Blog\Entity\BlogArticle", "CategoryId", EQUAL, $categoryId));
        $article->AddArgument(new Argument("Apps\Blog\Entity\BlogArticle", "Actif", EQUAL, 1));

        return count($article->GetByArg());
    }

    /*     * *
     * Sauvegarde une catégorie
     */

    public static function SaveCategory($core, $data) {

        $categoryForm = new BlogCategoryForm($core, $data);

        if ($categoryForm->Validate($data)) {

            $category = new BlogCategory($core);

            if ($data["Id"] != "") {
                $category->GetById($data["Id"]);
            } else {
                $blog = BlogHelper::GetFirst($core);
                $category->BlogId->Value = $blog->IdEntite;
            }

            $category->Code->Value = Format::ReplaceForUrl($data["Name"]);

            $categoryForm->Populate($category);
            $category->Save();

            return true;
        }

        return false;
    }

    /*
     * Supprime une catégorie
     */

    public static function DeleteCategory($core, $categoryId) {

        //Suppression de la categorie
        $categorie = new BlogCategory($core);
        $categorie->GetById($categoryId);
        $categorie->Delete();

        return true;
        //TODO supprimé les message liées
    }
}

?>
