<?php

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

namespace Core\Control\Form;

use Core\Control\IControl;
use Core\Control\Control;
use Core\Control\Upload\Upload;
use Core\View\View;
use Core\View\ElementView;
use Core\Core\Core;
use Core\Control\AutoCompleteBox\AutoCompleteBox;

class Form extends Control implements IControl {

    protected $Controls = array();
    protected $View;
    protected $Data;
    protected $Images = array();
    public $errors = array();
    protected $elementView = array();

    /**
     * 
     * @param type $name
     */
    function __construct($name, $data = "") {
        //Version
        $this->Version = "2.0.1.0";

        $this->Id = $name;
        $this->Name = $name;
        $this->Core = Core::getInstance();
        $this->Data = $data;
    }

    /**
     * Définie la vue utilisé
     */
    function SetView($view) {
        $this->View = $view;
    }

    /**
     * Ajoute un control
     */
    function Add($control) {
        $this->Controls[$control["Id"]] = $control;
    }

    /**
     * Ajoute un element de vue
     */
    function AddElementView($elementView) {
        $this->elementView[] = $elementView;
    }

    /**
     * Définie l'action
     */
    function SetAction() {
        
    }

    /**
     * Génére la balise Form ouvrante
     */
    function RenderOpen() {
        $html = "<form id='" . $this->Id . "' >";

        return $html;
    }

    /**
     * Génére la balise Form ouvrante
     */
    function RenderClose() {
        $html = "</form>";

        return $html;
    }

    /**
     * Génére la balise Form ouvrante
     */
    function RenderError() {
        $html = "<div class='error'></div>";

        return $html;
    }

    /**
     * Génére la balise Form ouvrante
     */
    function RenderSuccess() {
        $html = "<div class='success'></div>";

        return $html;
    }

    function RenderControl($html) {

        //Remplacement des proprietes
        $pattern = "`{{form->Render\((.+)\)}}`";
        preg_match_all($pattern, $html, $macthes);
        $i = 0;

        //  echo "<br/><br/>";
        //  echo "<pre>";       
        // var_dump($macthes);
        foreach ($macthes[0] as $match) {
            // echo $match;
            $name = $macthes[1][$i];

            if (isset($this->Controls[$name])) {
                $type = $this->Controls[$name]["Type"];

                if ($type == "Upload") {

                    //$app, $id ="", $callBack ="", $action = false, $idUpload ="fileToUpload"
                    $control = new Upload($this->Controls[$name]["App"],
                            $this->Controls[$name]["Id"],
                            "",
                            $this->Controls[$name]["Method"],
                            $this->Controls[$name]["Id"] . "fileToUpload"
                    );

                    if (isset($this->Controls[$name]["Accept"])) {
                        $control->Accept = $this->Controls[$name]["Accept"];
                    }

                    if (isset($this->Controls[$name]["Image"])) {
                        $control->Image = $this->Controls[$name]["Image"];
                    }
                    if (isset($this->Controls[$name]["ImageDefault"])) {
                        $control->ImageDefault = $this->Controls[$name]["ImageDefault"];
                    }
                    if (isset($this->Controls[$name]["Multiple"])) {
                        $control->Multiple = $this->Controls[$name]["Multiple"];
                    }
                    if (isset($this->Controls[$name]["Resize"])) {
                        $control->Resize = $this->Controls[$name]["Resize"];
                    }
                    if (isset($this->Controls[$name]["RemoveMethode"])) {
                        $control->RemoveMethode = $this->Controls[$name]["RemoveMethode"];
                    }

                    if (isset($this->Controls[$name]["BackgroudPositionY"])) {
                        $control->BackgroudPositionY = $this->Controls[$name]["BackgroudPositionY"];
                    }

                    if (isset($this->Controls[$name]["BackgroudPositionX"])) {
                        $control->BackgroudPositionX = $this->Controls[$name]["BackgroudPositionX"];
                    }
                } else if ($type == "AutoCompleteBox") {

                    //$app, $id ="", $callBack ="", $action = false, $idUpload ="fileToUpload"
                    $control = new AutoCompleteBox($this->Controls[$name]["Id"], $this->Core);
                    $control->Entity = $this->Controls[$name]["Entity"];
                    $control->Methode = $this->Controls[$name]["Methode"];
                    $control->SourceControl = $this->Controls[$name]["SourceControl"];
                } else {

                    $className = "Core\\Control\\" . $type . "\\" . $type;
                    $control = new $className($this->Controls[$name]["Id"], $this->Core);
                    $control->Id = $this->Controls[$name]["Id"];
                }

                if (isset($this->Controls[$name]["Name"])) {
                    $control->Name = $this->Controls[$name]["Name"];
                }

                if (isset($this->Controls[$name]["Checked"])) {
                    $control->Checked = $this->Controls[$name]["Checked"];
                }

                if (isset($this->Controls[$name]["Enabled"])) {
                    $control->Enabled = $this->Controls[$name]["Enabled"];
                }

                if (isset($this->Controls[$name]["Value"])) {
                    $control->Value = $this->Controls[$name]["Value"];
                    $control->Selected = $this->Controls[$name]["Value"];
                }
                if (isset($this->Controls[$name]["CssClass"])) {
                    $control->CssClass = $this->Controls[$name]["CssClass"];
                }

                //EntityListBox
                if (isset($this->Controls[$name]["Entity"])) {

                    $control->Entity = $this->Controls[$name]["Entity"];

                    if (isset($this->Controls[$name]["Field"])) {
                        $control->AddField($this->Controls[$name]["Field"]);
                    }

                    if (isset($this->Controls[$name]["Fields"])) {
                        foreach ($this->Controls[$name]["Fields"] as $fieldName) {
                            $control->AddField($fieldName);
                        }
                    }

                    if (isset($this->Controls[$name]["Values"])) {
                        foreach ($this->Controls[$name]["Values"] as $key => $value) {
                            $control->ListBox->Add($this->Core->GetCode($value), $key);
                        }
                    }
                    if (isset($this->Controls[$name]["Filter"])) {
                        $control->Filter = $this->Controls[$name]["Filter"];
                    }
                    if (isset($this->Controls[$name]["Multiple"])) {
                        $control->Multiple = $this->Controls[$name]["Multiple"];
                    }
                    
                    if (isset($this->Controls[$name]["TextValue"])) {
                        $control->TextValue = $this->Controls[$name]["TextValue"];
                    }

                    if (isset($this->Controls[$name]["Data"])) {
                        $control->Data = $this->Controls[$name]["Data"];
                    }

                    if (isset($this->Controls[$name]["Argument"])) {

                       if(is_array($this->Controls[$name]["Argument"])){

                        foreach($this->Controls[$name]["Argument"] as $argument){
                            $control->AddArgument($argument);
                        }
                       } else {

                        $control->AddArgument($this->Controls[$name]["Argument"]);
                       }
                    }
                }
    
                if (isset($this->Controls[$name]["Attributs"])) {
                    foreach ($this->Controls[$name]["Attributs"] as $key => $value) {
                        $control->AddAttribute($key, $value);
                    }
                }

                if (isset($this->Controls[$name]["Validators"])) {
                    $control->Validators = implode("|", $this->Controls[$name]["Validators"]);
                }

                if (isset($this->Controls[$name]["Values"])) {
                    $control->Options = $this->Controls[$name]["Values"];
                }

                if (isset($this->Controls[$name]["PlaceHolder"])) {
                    $control->PlaceHolder = $this->Controls[$name]["PlaceHolder"];
                }

                if (isset($this->Controls[$name]["Style"])) {
                    $control->Style = $this->Controls[$name]["Style"];
                }

                $html = str_replace($match, $control->Show(), $html);
            }
//$html .= $match;

            $i++;
        }

        return $html;
    }

    /*     * *
     * Affiche les images
     */

    function RenderImage() {

        $html = "<div class='imagesContainer'>";

        foreach ($this->Images as $image) {

            if (!strstr($image, "_96")) {
                $html .= "<div><img style='width:50px' src='" . $image . "' /><i class='fa fa-times' onclick='Form.RemoveImage(this);' >&nbsp;</i></div>";
            }
        }

        $html .= "</div>";

        return $html;
    }

    /*     * *
     * Affiche les documents
     */

     function RenderDocument() {

        $html = "<div class='documentsContainer'>";

        foreach ($this->Documents as $document) {

                $html .= "<div>" .$document. "<i class='fa fa-times' onclick='Form.RemoveImage(this);' >&nbsp;</i></div>";
                //$html .= "<div><img style='width:50px' src='" . $image . "' /><i class='fa fa-times' onclick='Form.RemoveImage(this);' >&nbsp;</i></div>";
        }

        $html .= "</div>";

        return $html;
    }

    /*     * *
     * Génére le html du formulaire
     */

    function Render() {
        $view = new View($this->View, $this->Core);
        $view->AddElement($this);

        foreach ($this->elementView as $element) {
            $view->AddElement($element);
        }

        return $view->Render();
    }

    /**
     * Charges les différents controles avec les données de l'entity
     * @param type $entity
     */
    function Load($entity) {
        foreach ($this->Controls as $key => $control) {
            $name = $control["Id"];

            if ($key == "Id") {
                $this->Controls[$key]["Value"] = $entity->IdEntite;
            } else {
                if (isset($entity->$name)) {

                    //Pour les types dates il faut inverser
                    if ($this->Controls[$key]["Type"] == "DateBox") {
                        $dates = explode("/", $entity->$name->Value);
                        $this->Controls[$key]["Value"] = $dates[2] . "-" . $dates[1] . "-" . $dates[0];
                    } 
                    if ($this->Controls[$key]["Type"] == "CheckBox") {
                        $this->Controls[$key]["Checked"] = $entity->$name->Value;
                    }
                    else {
                        $this->Controls[$key]["Value"] = $entity->$name->Value;
                    }
                }
            }
        }
    }

    /*     * *
     * Récupéres les images de l'entite
     */

    function LoadImage($entity) {
        $this->Images = $entity->GetImages();
    }
 
    /****
     * Récupe les documents
     */
    function LoadDocument($entity) {
        $this->Documents = $entity->GetDocuments();
    }
    
    /**
     * Valide ces données selon les Controles Ajoutés
     */
    function Validate($data = "") {
        foreach ($this->Controls as $control) {
            $validators = $control["Validators"];

            foreach ($validators as $validator) {

                switch ($validator) {
                    case "Required";

                        if ($control["Type"] == "Upload") {
                            //dvUpload-imageToUploadFacefileToUpload
                            $controlName = "dvUpload-" . $control['Id'] . "fileToUpload";

                            if (!isset($data[$controlName]) || $data[$controlName] == "") {
                                $this->errors[] = $control['Id'] . " " . $this->Core->GetCode("Required");
                            }
                        } else if (!isset($data[$control['Id']]) || $data[$control['Id']] == "") {
                            $this->errors[] = $control['Id'] . " " . $this->Core->GetCode("Required");
                        }
                        break;
                }
            }
        }

        if (count($this->errors) > 0) {
            return false;
        } else {
            return true;
        };
    }

    /*     * *
     * Retourne les success au format JSON
     */

    function Success($data) {
        return json_encode(array("statut" => "Success", "data" => $data));
    }

    /*     * *
     * Retournes les erreurs au format JSON
     */

    function Error() {
        return json_encode(array("statut" => "Error", "message" => $this->errors));
    }

    /**
     * Retourne une des variable
     */
    function Get($name) {
        return $this->Data[$name];
    }
}

?>