<?php

namespace Apps\Forum;

use Core\App\Application;
use Core\Core\Core;
use Core\Core\Request;
use Core\Core\Response;
use Core\Utility\Format\Format;

use Apps\Forum\Entity\ForumForum;
use Apps\Forum\Helper\CategoryHelper;
use Apps\Forum\Helper\ForumHelper;
use Apps\Forum\Helper\MessageHelper;
use Apps\Forum\Helper\SitemapHelper;
use Apps\Forum\Helper\NotifyHelper;
use Apps\Forum\Entity\ForumMessage;

use Apps\Forum\Module\Admin\AdminController;
use Apps\Forum\Module\Category\CategoryController;
use Apps\Forum\Module\Forum\ForumController;
use Apps\Forum\Module\Message\MessageController;
use Apps\Forum\Module\Widget\WidgetController;
use Apps\Forum\Module\Member\MemberController;



/**
 * Application de gestion des forums
 * */
class Forum extends Application {

    /**
     * Auteur et version
     * */
    public $Author = 'DashBoardManager';
    public $Version = '2.1.2.0';
    public static $Directory = "Apps/Forum";

    /**
     * Constructeur
     * */
    function __construct() {
        $this->Core = Core::getInstance();
        parent::__construct($this->Core, "Forum");
    }

     /**
     * Set the Public Routes
     */
     public function GetRoute()
     {
        // Temporairement ajouté plus de routes publiques pour faciliter le débogage
        $this->Route->SetPublic(array(
            "Category", 
            "Sujet", 
            "NewDiscussion",
            "ShowAddReponse", 
            "SaveReponse",
            "UpdateReponse",
            "DeleteReponse"
        ));
       
        return $this->Route;
     }
     
     /***
      * Execute action after install
      */
     function PostInstall() {
        \Apps\EeApp\Helper\AppHelper::UpdateAppParams($this->Core,
                "Forum",
                $this->Version,
                "Application de forum.",
                1,
                1
        );
    }
     
    /*
     * Front Home Page
     */
    function Index()
    {
        $this->Core->MasterView->Set("Title", "Forum");
        return $this->ShowDefaultForum(false);
    }
    
    /*
     * Front category page
     */
    function Category($params)
    {
        $frontController = new ForumController($this->Core);
        return $frontController->ShowMessages($params, null, true, true);
    }
    
    /*
     * Show message 
     */
    function Sujet($params)
    {
        $forumController = new ForumController($this->Core);
        $html = $forumController->ShowMessage($params, true);

        if(Request::GetPost("Message"))
        {
           $message = new ForumMessage($this->Core);
           $message = $message->GetByCode($params);
          
            //Send notify to the User
            NotifyHelper::NewResponse($this->Core, $message);
            
            $this->Core->Redirect($this->Core->GetPath("/Forum/Sujet/" .$params ));
        }
        else
        {
            return $html;
        }
    }
   
    /*
     * Add  discussion
     */
    function NewDiscussion($params)
    {
        $this->Core->MasterView->Set("Title", $this->Core->GetCode("Forum.NewDiscussion"));
        
        $forumController = new ForumController($this->Core);
        $html = $forumController->NewDiscussion($params);

        if(Request::GetPost("Title"))
        {
            $this->Core->Redirect($this->Core->GetPath("/Forum/Sujet/" .Format::ReplaceForUrl(Request::GetPost("Title"))));
        }
        else
        {
            return $html;
        }
    }
    
    /**
     * Execution de l'application
     */
    function Run() {
        echo parent::RunApp($this->Core, "Forum", "Forum");
    }

    /***
     * Run member Controller
     */
    function RunMember(){
        $memberController = new MemberController($this->Core);
        return $memberController->Index();
    }
 
    /**
     * Enregistre un nouveau forum
     */
    function SaveForum() {
        
        $adminController = new AdminController($this->Core);
        return $adminController->SaveForum(Request::GetPosts());
    }

    /*     * *
     * Sauvegarde la catégorie
     */

    function SaveCategory() {
        $adminController = new AdminController($this->Core);
      
        if ($adminController->SaveCategory(Request::GetPosts())) {
            
            $forum = ForumHelper::GetFirst($this->Core);
            
            return Response::Success($adminController->GetTabCategory($forum));
        } else {
            return Response::Error();
        }
    }
    


    /*     * *
     * Supprime une catégorie
     */

    function DeleteCategory() {
        if (CategoryHelper::DeleteCategory($this->Core, Request::GetPost("categoryId"))) {

            $forum = ForumHelper::GetFirst($this->Core);
            $adminController = new AdminController($this->Core);
            return Response::Success($adminController->GetTabCategory($forum));
        } else {
            return Response::Error();
        }
    }
  
    /*
     * Update a message
     * 
     */
    function UpdateMessage() {
        if (MessageHelper::UpdateMessage($this->Core, Request::GetPosts())) {
           
            $adminController = new AdminController($this->Core);
            return Response::Success($adminController->GetTabMessage($forum));
        } else {
            return Response::Error();
        }
    }
    
    /*     * *
     * Supprime un message
     */

    function DeleteMessage() {
        if (MessageHelper::DeleteMessage($this->Core, Request::GetPost("messageId"))) {

            $forum = ForumHelper::GetFirst($this->Core);
            $adminController = new AdminController($this->Core);
            return Response::Success($adminController->GetTabMessage($forum));
        } else {
            return Response::Error();
        }
    }
  
    /***
     * Delete a reponse
     */
    function DeleteReponse(){
        MessageHelper::DeleteReponse($this->Core, Request::GetPost("reponseId"));
    }

    /**
     * Update a reponse
     */
    function UpdateReponse(){
        MessageHelper::UpdateReponse($this->Core, Request::GetPosts());
    }
    /*
     * Affiche le forum par defaut
     */

    function ShowDefaultForum($show = true)
    {
        //TODO POuvoir parametrer un forum par défaut
        $forum = ForumHelper::GetFirst($this->Core);

        $forumController = new ForumController($this->Core);
        $html = $forumController->ShowForum($forum->Name->Value, "", Request::GetPost("categoryId"), Request::GetPost("messageId"), $show);
        
        if($show)
            echo $html; 
        else
            return $html; 
    }

    /*
     * Affiche un forum
     */

    function ShowForum($forum, $idEntite, $category, $sujet) {
        $forumController = new ForumController($this->Core);
        return $forumController->ShowForum($forum, $idEntite, $category, $sujet);
    }

    /**
     * Pop in d'ajout de message
     */
    function ShowAddSujet() {
        $messageController = new MessageController($this->Core);
        echo $messageController->ShowAddSujet(Request::GetPost("CategoryId"));
    }

    /**
     * Enregistrement d'un nouvell discussion
     */
    function SaveDiscussion() {
        $title = Request::GetPost("tbTitle");
        $message = Request::GetPost("tbMessage");
        $categoryId = Request::GetPost("CategoryId");

        if ($title != "" && $message != "") {
            MessageHelper::Save($this->Core, $categoryId, $title, $message);

            echo "<span class='success'>" . $this->Core->GetCode("Forum.DiscussionSaved") . "</span>";
        } else {
            echo "<span class='error'>" . $this->Core->GetCode("Forum.ErrorDiscussion") . "</span>";

            $this->ShowAddSujet();
        }
    }

    /****
     * Add a new Messages in the Forum
     */
    function NewMessage(){
      
        if(MessageHelper::NewMessage($this->Core, Request::GetPosts())){
            return Response::Success(array());
        } else{
            return Response::Success(array());
      }  
    }

    /**
     * Pop in d'ajout d'une réponse
     */
    function ShowAddReponse() {
        $messageController = new MessageController($this->Core);
        echo $messageController->ShowAddReponse(Request::GetPost("SujetId"));
    }

    /**
     * Sauvegarde la réponse
     */
    function SaveReponse() {
        $message = Request::GetPost("tbMessage");
        $sujetId = Request::GetPost("SujetId");

        if ($message != "") {
            MessageHelper::SaveReponse($this->Core, $sujetId, $title, $message);

            echo "<span class='success'>" . $this->Core->GetCode("Forum.ReponseSaved") . "</span>";
        } else {
            echo "<span class='error'>" . $this->Core->GetCode("Forum.ErrorReponse") . "</span>";

            $this->ShowAddReponse();
        }
    }

    /**
     * Rafraichit la liste des messages d'un categorie
     */
    function RefreshMessage() {
        $forumController = new ForumController($this->Core);
        echo $forumController->ShowMessages("", Request::GetPost("categoryId"), false);
    }

    /**
     * Rafraichit la listes des éponses
     */
    function RefreshReponse() {
        $forumController = new ForumController($this->Core);

        //Recuperation de l'appli Profil
        $eProfil = new Forum($this->Core);

        echo $forumController->ShowReponses(Request::GetPost("sujetId"), $eProfil);
    }

    /*
     * Charge la partie administration du forum
     */

    function LoadAdmin() {
        $adminController = new AdminController($this->Core);
        echo $adminController->Show();
    }

      /**
     * Get The siteMap 
     */
    public function GetSiteMap($url = false){
        return SitemapHelper::GetSiteMap($this->Core, $url);
    }

    /***
     * Get the widget
     */
    public function GetWidget($type = "", $params = "") {
   
        switch ($type) {
            case "AdminDashboard" :
                $widget = new \Apps\Forum\Widget\AdminDashBoard\AdminDashBoard($this->Core);
                break;
            case "LastMessage" :
                $widget = new \Apps\Forum\Widget\LastMessageWidget\LastMessageWidget($this->Core);
                break;
        }
        
        return $widget->Render();
    }
    
     /***
     * Get Forum Addable widget
     */
    public function GetListWidget(){
       return array(array("Name" => "LastMessage", 
                           "Description" => $this->Core->GetCode("Forum.DescriptionLastMessageWidget")),
                    );
    }
    
    /********************* API *************************************/
    
    /***
     * Obtient les catégories et avec leur dérniers messages
     */
    public function GetCategories(){
        
         $forum = ForumHelper::GetFirst($this->Core);
          
         return Response::Success(CategoryHelper::GetByForum($this->Core, $forum->IdEntite, true));
    }
    
    /***
     * Obtient la catégorie et tous les messages
     */
    public function GetCategorie(){
        return Response::Success(CategoryHelper::GetCategory($this->Core, Request::GetPost("categoryId")));
    }
    
    /***
     * Obtient un message et ses réponses
     */
    public function GetMessage(){
        return Response::Success(MessageHelper::GetMessage($this->Core, Request::GetPost("messageId")));
    }
      
    /***
     * Envoie une question 
     */
    public function SendQuestion(){
        MessageHelper::Save($this->Core, Request::GetPosts());
        
        return $this->GetMessage();
    }
    
    /***
     * Envoie une réponse 
     */
    public function SendReponse($params, $userId){
        MessageHelper::SaveReponse($this->Core, 
                                   Request::GetPost("MessageId"),
                                   Request::GetPost("Message"),
                                   $userId 
                                );
        
        return $this->GetMessage();
    }
    
    /***
     * Get list of Email can be user ine Newsletter
     */
    public function GetListEmail(){
        return array("NewResponseMessage");
    }
    
     /***
     * Detail d'une notification
     */
    public function GetDetailNotify($notify){
       return NotifyHelper::GetDetailNotify($this->Core, $notify);
    }
}

?>