<?php

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

namespace Apps\Blog\Helper;

use Apps\Blog\Helper\BlogHelper;
use Apps\Blog\Entity\BlogCategory;
use Apps\Blog\Entity\BlogArticle;
use Core\Utility\Date\Date;

class ImportHelper {

        public static function ImportCategory($core, $category) {

        $message = "Import de la catégorie " . $category->Name;

        $currentCategorie = new BlogCategory($core);
        $currentCategorie = $currentCategorie->GetByCode($category->Code);
        $blog = BlogHelper::GetFirst($core);
  
        if ($currentCategorie == null) {
            $newCategorie = new BlogCategory($core);
            $newCategorie->BlogId->Value = $blog->IdEntite;
            $newCategorie->Name->Value = $category->Name;
            $newCategorie->Code->Value = $category->Code;
            $newCategorie->Description->Value = $category->Description;
            $newCategorie->Save();
            $categoryId = $core->Db->GetInsertedId();
            
        } else {
            $categoryId = $currentCategorie->IdEntite;
        }

        foreach ($category->Articles as $article) {
            $message .= self::ImportArticle($core, $article, $categoryId, $blog->IdEntite);
        }

        return $message;
    }

    /*     * *
     * Import Article
     */

    public static function ImportArticle($core, $article, $categoryId, $blogId) {

        $currentArticle = new BlogArticle($core);
        $currentArticle = $currentArticle->GetByCode($article->Code);

        if ($currentArticle == null) {
            $newArticle = new BlogArticle($core);
            $newArticle->Name->Value = $article->Name;
            $newArticle->Code->Value = $article->Code;
            $newArticle->BlogId->Value = $blogId;
            $newArticle->CategoryId->Value = $article->CategoryId;
            $newArticle->Actif->Value = $article->Actif;
            $newArticle->UserId->Value = $core->User->IdEntite;
            $newArticle->DateCreated->Value = Date::Now();
        } else {
            $newArticle = $currentArticle;
        }


        $newArticle->Actif->Value = $article->Actif;
        $newArticle->KeyWork->Value = $article->KeyWork;
        $newArticle->Description->Value = $article->Description;
        $newArticle->Content->Value = $article->Content;
        
        $newArticle->Save();
    }
}
