<?php

namespace Apps\Forum\Widget\MessageForm;

use Core\Control\Form\Form;
use Core\View\View;
use Core\View\ElementView;
use Core\Control\EntityGrid\EntityGrid;
use Core\Control\EntityGrid\EntityColumn;
use Core\Control\EntityGrid\EntityIconColumn;
use Core\Control\EntityGrid\EntityFunctionColumn;
use Core\Entity\Entity\Argument;
use Core\Utility\Date\Date;
use Core\Utility\Format\Format;
use Core\Core\Request;

class MessageForm extends Form {
    
    /**
     * Category of the message
     */
    private $category;
    
    /**
     * State of the model - requis par ViewModelManager
     */
    protected $State = "Init";
    
    /**
     * Exclude Field - requis par ViewModelManager 
     */
    protected $Excludes = array();
    
    /**
     * Element Type hidden - requis par ViewModelManager
     */
    protected $Elements = Array();

    /**
     * Constructeur
     */
    function __construct($core = "", $data = "") {
        $this->Core = $core;
        $this->Data = $data;

        //On le fait ici pour avoir le formulaire à l'affichage mais aussi à la validation
        $this->Init($data);
        
        // Pour compatibilité avec l'ancien MessageModel
        if ($core) {
            $entityName = "Apps\Forum\Entity\ForumMessage";
            $this->Entity = new $entityName($core);
        }
    }

    /**
     * Initialisation 
     */
    function Init($data) {
        $this->form = new Form("MessageFormForm", $data);

        $this->form->SetView(__DIR__ . "/View/index.tpl", $this->Core);
        $this->form->SetAction("/View/index.tpl");

        $this->form->Add(array("Type" => "Hidden",
            "Id" => "Id",
        ));
        
        $this->form->Add(array("Type" => "TextBox",
            "Id" => "Title",
            "Validators" => ["Required"]
        ));
        
        
        $this->form->Add(array("Type" => "TextArea",
            "Id" => "Message",
            "Validators" => ["Required"]
        ));
        
        $this->form->Add(array("Type" => "Button",
            "Id" => "btnSaveMessage",
            "Value" => $this->Core->GetCode("Forum.UpdateMessage"),
            "CssClass" => "btn btn-primary"
        ));
        
        $messageId = (is_array($data) && isset($data["Id"])) ? $data["Id"] : null;
        $this->form->AddElementView(new ElementView("gdReponse", $this->GetGridReponse($messageId)));
    }

     //Message of all Forum
     function GetGridReponse($messageId){
        $gdReponse = new EntityGrid("gdReponse", $this->Core);
        $gdReponse->Entity = "Apps\Forum\Entity\ForumReponse";
        
        if ($messageId !== null) {
            $gdReponse->AddArgument(new Argument("Apps\Forum\Entity\ForumReponse", "MessageId", EQUAL, $messageId));
        }
        
        $gdReponse->App = "Forum";
        $gdReponse->Action = "GetTabMessage";
        $gdReponse->AddOrder("DateCreated desc");
  
        $gdReponse->AddColumn(new EntityColumn("DateCreated", "DateCreated"));
        $gdReponse->AddColumn(new EntityFunctionColumn("Message", "GetEditableMessage"));
       
        
        $gdReponse->AddColumn(new EntityIconColumn("Action", 
                                                  array(array("EditIcone", "Forum.EditReponse", "MessageForm.EditReponse"),
                                                        array("DeleteIcone", "Forum.DeleteReponse", "MessageForm.DeleteReponse"),
                                                  )    
                          ));
  
        return $gdReponse->Render();
     }
     
    
    
    /*     * *
     * Générer les formulaire
     */
    function Render() {
        return $this->form->Render();
    }
    
    /**
     * Cette méthode est utilisée avec {{RenderModel()}} dans les templates
     * et doit être présente pour respecter l'API du ViewModelManager
     */
    public static function RenderModel($html, $model, $ajax = false, $app = null, $action = null, $class = null, $callBack = null) 
    {
        if (method_exists($model, 'Prepare')) {
            $model->Prepare();
        }
        
        return \Core\View\ViewModelManager::RenderModelDefault($html, $model, $ajax, $app, $action, $class, $callBack);
    }

    /*     * *
     * Valide les donn�es selon les diff�rents formulaires
     */

    function Validate($data = "") {
        $errors = $this->form->Validate($this->Data);

        return $errors;
    }

    /*     * *
     * Charge les controls avec les donn�es de l'entit�
     */

    function Load($entity) {
        $this->form->Load($entity);
    }

    /*     * *
     * Charge l'entité avec les données des différents formulaires
     */

    function Populate($entity) {
        foreach ($this->form->Controls as $control) {
            if (property_exists($entity, $control->Id)) {
                $entity->{$control->Id}->Value = $control->Value;
            }
        }
    }

    /*     * *
     * Gestion des erreurs
     */

    function Error() {
        $errors[] = $this->form->errors;

        return json_encode(array("statut" => "Error", "message" => $errors));
    }
    
    /**
     * Set The category
     */
    public function SetCategory($category)
    {
       $this->category = $category;
    }
    
    /**
     * Prepare the form - exclure les champs qui ne doivent pas être affichés
     */
    public function Prepare()
    {
        $this->Exclude(array("CategoryId", "Code", "UserId", "Core\Entity\User\User", "Apps\Forum\Entity\ForumCategory", "DateCreated"));
    }
    
    /**
     * Exclude fields from entity
     */
    public function Exclude($fields)
    {
        if (isset($this->Entity) && $this->Entity) {
            foreach ($fields as $field) {
                if (property_exists($this->Entity, $field)) {
                    $this->Entity->$field->Exclude = true;
                }
            }
        }
    }
    
    /**
     * Return the Entity - méthode requise par ViewModelManager
     */
    public function GetEntity()
    {
       return $this->Entity;
    }
    
    /**
     * Return the state - méthode requise par ViewModelManager
     */
    public function GetState()
    {
        return $this->State;
    }
    
    /**
     * Get Field Exclude - méthode requise par ViewModelManager
     */
    public function GetExcludes()
    {
        return $this->Excludes;
    }
    
    /**
     * Return the elements - méthode requise par ViewModelManager
     */
    public function GetElements()
    {
        return $this->Elements;
    }
    
    /**
     * Add Element - méthode requise par ViewModelManager
     */
    public function AddElement($key, $value)
    {
        $this->Elements[$key] = $value;
    }
    
    /**
     * Save/update the entity 
     */
    public function Updated()
    {
        if (Request::IsPost() && isset($this->Entity) && $this->Entity) {
            $title = Request::GetPost("Title");
            $message = Request::GetPost("Message");
            
            if (!empty($title)) {
                $this->Entity->Title->Value = $title;
            }
            
            if (!empty($message)) {
                $this->Entity->Message->Value = $message;
            }
            
            $this->Entity->CategoryId->Value = $this->category->IdEntite;
            $this->Entity->UserId->Value = $this->Core->User->IdEntite;
            $this->Entity->DateCreated->Value = Date::Now();
            $this->Entity->Code->Value = Format::ReplaceForUrl($title);
            
            try {
                $result = $this->Entity->Save();
                if ($result) {
                    $this->State = "Updated";
                    return true;
                }
            } catch (\Exception $e) {
                $this->form->errors[] = $e->getMessage();
            }
        }
        $this->State = "Init";
        return false;
    }
}
