<?php

/**
 * PuzzleApp 
 * PuzzleApp.org - The Hybride Framework.
 * Oliva Jérôme
 * GNU Licence
 * */

namespace Core\Core;

use Core\Core\Config;
use Core\Core\DataBase;
use Core\Core\Request;
use Core\Entity\Group\Group;
use Core\Entity\User\User;
use Core\Entity\Entity\Argument;

//Inclusion of the class of core
include "Constante.php";

class Core {

    /**
     *
     * @var SingletonClass
     */
    private static $_instance;
    //Property
    protected $Include;
    protected $Page;
    protected $Entity;
    protected $JDirectory;
    protected $UserGroupe;
    protected $Version;
    protected $PackageVersion;
    protected $DataBaseEnabled;
    //Accessible property
    public $Config;
    public $User;
    public $App;
    public $Db;
    public $MasterModel;
    public $Debug;
    public $ConfigFile;
    public $Lang;

    /**
     * Get the singleton of the core
     *
     * @return SingletonClass
     */
    public static function getInstance($config = "", $debug = false) {
        if (true === is_null(self::$_instance)) {
            self::$_instance = new self(true, "", "", "", $config);
            self::$_instance->Debug = $debug;
            self::$_instance->ConfigFile = $config;
        }

        return self::$_instance;
    }

    /*
     * Construct the Core
     */

    function __construct($include, $typeDb = "", $file = "", $directory = "", $configFile = "") {
        
    }

    /*
     * Define if the app can run
     */

    public function IsInstalled() {
        //Verify the Key Instal in the Config file
        $this->Config = new Config("../Config/" . self::$_instance->ConfigFile . ".xml");
        return $this->Config->GetKey("INSTALLED") == 1;
    }

    /*
     * Init the core
     */

    function init() {
        //Version du coeur
        $this->Version = "2.3.2.0";
        $this->PackageVersion = "2.0.2.0";
        
        try {
            $this->Config = new Config("../Config/" . self::$_instance->ConfigFile . ".xml");

            if ($this->Config->GetKey("DATABASESERVER") != "") {
                $this->DataBaseEnabled = true;

                //Data Base
                $this->Db = new DataBase(
                        $this->Config->GetKey("DATABASESERVER"),
                        $this->Config->GetKey("DATABASENAME"),
                        $this->Config->GetKey("DATABASELOGIN"),
                        $this->Config->GetKey("DATABASEPASS")
                );

                //Get Language
                $this->Lang = new Language($this);

                //Default language
                if (Request::GetSession("Lang") == "" && !isset($_COOKIE["puzzleAppLang"])) {
                    
                    $langConfig = $this->Config->GetKey("LANG");  
                    
                    $lang = $langConfig != false ?  $this->Config->GetKey("LANG") :  "En";
                    
                    Request::SetSession("Lang", (string)$lang[0]);
                    
                    //Enregistrement du cookie en session
                    setcookie("puzzleAppLang", $lang, time() + (86400 * 30), "/");
                }
            } else {
                $this->DataBaseEnabled = false;
            }

            if (Request::IsConnected($this) && $this->DataBaseEnabled) {
                $this->User = new User($this);
                $this->User->GetById(Request::GetUser($this));
            }
        } catch (Exception $e) {
            var_dump($e);
            echo "ERREUR" . $e->GetMessage();
            Log::Title(CORE, "Erreur", ERR);
            Log::Write(CORE, $e->GetMessage(), ERR);
            throw new Exception($e->GetMessage());
        }
    }

    /*
     * Connect the use
     */

    function Connect($user) {
        //Store the user in the session
        Request::Connect($user);

        //Update the user
        $this->User = $user;
    }

    /**
     * Define if user is Admin
     */
    function IsAdmin() {

        if ($this->IsConnected()) {
            return $this->User->Groupe->Value->Section->Value->Directory->Value == "Admin";
        }

        return false;
    }

    /*
     * Disconnect the use
     */

    function Disconnect() {
        Request::Disconnect($this);

        $this->Redirect("index");
    }

    /*
     * Défine if the user is connected
     */

    function IsConnected() {
        return Request::IsConnected($this);
    }

    //Verifie les droits utilisateurs
    private function NeedConnection($Group) {
        if (!empty($Group)) {
            if ($Group == Request::GetUserGroup($this))
                return true;
            else
                return false;
        } else {
            return true;
        }
        Log::Write(CORE, "Connection", INFO);
    }

    /*     * *
     * @deprecated
     */

    function GetJDirectory() {
        return $this->JDirectory;
    }

    /**
     * Return the core version
     * @return type
     */
    function GetVersion() {
        return $this->Version;
    }

    /***
     * Return the package version
     */
    function GetPackageVersion() {
        return $this->PackageVersion;
    }
    
    
    /*     * *
     * Return à translate text in the current lang
     */

    function GetCode($code) {
        if ($this->DataBaseEnabled)
            return $this->Lang->GetCode($code, $this->GetLang());
        else
            return $code;
    }

    /*
     * Return the complete path
     */

    function GetPath($url) {
        if ($_SERVER["HTTPS"]) {
            return "https://" . $_SERVER['SERVER_NAME'] . $url;
        } else {
            return "http://" . $_SERVER['SERVER_NAME'] . $url;
        }
    }

    /*     * *
     * Return all Code
     */

    function GetAllCode() {
        return $this->Lang->GetAllCode($this->GetLang());
    }

    /**
     * 
     * @param type $code
     * @return type
     */
    function GetLang($code = "") {
        
        //Retourne le code de la langue choisi
        if ($code == "") {
            
           if(isset($_COOKIE["puzzleAppLang"])){
              Request::SetSession("Lang", $_COOKIE["puzzleAppLang"]);
          }

          return Request::GetSession("Lang");
        }
        //Retourne l'identifiant
        else {
            $Lang = new \Core\Entity\Langs\Langs($this);
            $Lang->AddArgument(new Argument("Core\Entity\Langs\Langs", "Code", EQUAL, Request::GetSession("Lang")));
            $Langs = $Lang->GetByArg();

            if (sizeof($Langs) > 0)
                return $Langs[0]->IdEntite;
        }
    }

    /*     * *
     * Set the language
     */

    function SetLang($lang) {
        Request::SetSession("Lang", $lang);
        
        setcookie("puzzleAppLang", $lang, time() + (86400 * 30), "/");
    }

    /**
     * Get the script directory
     * @return type
     */
    function GetJsScript() {
        return $this->GetJDirectory() . "Jscripts/";
    }

    /*     * *
     * Return site name
     */

    function GetSiteName() {
        return $this->Config->GetKey("SITENAME");
    }

    /*     * *
     * @deprecated
     */

    function GetAction() {
        //Ouverture du fichier
        $Document = new JDOMDocument();
        $Document->load($this->GetJDirectory() . "/Action/Action.xml");

        //Recuperation des elements
        $Action = $Document->GetElementsByTagName("ELEMENT");
        $Actions = array();

        //Ajout
        foreach ($Action as $action) {
            $Actions[] = $action->nodeValue;
        }
        return $Actions;
    }

    /*     * *
     * @deprecated
     */

    function GetControl($DynamicAdd = false) {
        //Ouverture du fichier
        $Document = new JDOMDocument();
        $Document->load($this->GetJDirectory() . "/Control/Control.xml");

        //Recuperation des elements
        $Control = $Document->GetElementsByTagName("ELEMENT");

        $Controls = array();
        //Ajout
        foreach ($Control as $control) {
            if (is_object($control) and $control->nodeValue != "JHomControl") {
                if (($DynamicAdd && $control->getAttribute("DynamicAdd") == "True") || !$DynamicAdd) {
                    $Controls[] = $control->nodeValue;
                }
            }
        }
        return $Controls;
    }

    /*     * *
     * 
     */

    function GetModule($DynamicAdd = false) {
        //Ouverture du fichier
        $Document = new JDOMDocument();
        $Document->load($this->GetJDirectory() . "/Block/Block.xml");

        //Recuperation des elements
        $Module = $Document->GetElementsByTagName("ELEMENT");

        $Modules = array();
        //Ajout
        foreach ($Module as $module) {

            if (is_object($module) and $module->nodeValue != "JHomBlock") {
                if (($DynamicAdd && $module->getAttribute("DynamicAdd") == "True") || !$DynamicAdd) {
                    $Modules[] = $module->nodeValue;
                }
            }
        }
        return $Modules;
    }

    /*     * *
     * Get the user Tools
     */

    function GetTools($DynamicAdd = false) {
        //Ouverture du fichier
        $Document = new JDOMDocument();
        $Document->load($this->GetJDirectory() . "/Block/Block.xml");

        //Recuperation des elements
        $Module = $Document->GetElementsByTagName("ELEMENT");

        $Modules = array();
        //Ajout
        foreach ($Module as $module) {
            if (is_object($module) and $module->nodeValue != "JHomBlock") {
                if (($module->getAttribute("Tool") == "True" && $module->getAttribute("Actif") == "True")) {
                    $Modules[] = $module->nodeValue;
                }
            }
        }
        return $Modules;
    }

    /**
     * 
     * @return type
     */
    function GetEntite() {
        //Ouverture du fichier
        $Document = new JDOMDocument();
        $Document->load($this->GetJDirectory() . "/Entity/Entity.xml");

        //Recuperation des elements
        $Entity = $Document->GetElementsByTagName("ELEMENT");
        $Entitys = array();

        //Ajout
        foreach ($Entity as $entity) {
            if ($entity->getAttribute("className") != "") {
                $Entitys[] = $entity->getAttribute("className");
            } else {
                $Entitys[] = $entity->nodeValue;
            }
        }
        return $Entitys;
    }

    /*     * *
     * 
     */

    function GetPage() {
        //Ouverture du fichier
        $Document = new JDOMDocument();
        $Document->load($this->GetJDirectory() . "/Page/Page.xml");

        //Recuperation des elements
        $Page = $Document->GetElementsByTagName("ELEMENT");
        $Pages = array();

        //Ajout
        foreach ($Page as $page) {
            $Pages[] = $page->nodeValue;
        }
        return $Pages;
    }

    /*     * *
     * 
     */

    function GetUtility() {
        //Ouverture du fichier
        $Document = new JDOMDocument();
        $Document->load($this->GetJDirectory() . "/Utility/Utility.xml");

        //Recuperation des elements
        $Utility = $Document->GetElementsByTagName("ELEMENT");
        $Utilitys = array();

        //Ajout
        foreach ($Utility as $utlity) {
            $Utilitys[] = $utlity->nodeValue;
        }
        return $Utilitys;
    }

    /**
     * 
     * @return type
     */
    function GetTemplate() {
        //Ouverture du fichier
        $Document = new JDOMDocument();
        $Document->load($this->GetJDirectory() . "/Template/Template.xml");

        //Recuperation des elements
        $Template = $Document->GetElementsByTagName("ELEMENT");
        $Templates = array();

        //Ajout
        foreach ($Template as $template) {
            $Templates[] = $template->nodeValue;
        }
        return $Templates;
    }

    /**
     * Get the admin User
     * @return type
     */
    function GetAdminUser() {
        //Recuperation groupeAdmin
        $Group = new Group($this);
        $Group = $Group->GetByName("Admin");

        $User = new User($this);
        $User->AddArgument(new Argument("Core\Entity\User\User", "GroupeId", EQUAL, $Group->IdEntite));
        $Users = $User->GetByArg();

        return $Users;
    }

    /*     * *
     * Redirect to the url
     */

    function Redirect($Url) {
        if (!headers_sent())
            header("Location:$Url");
        else
            echo "<script type='text/javascript'>window.location.replace('$Url');</script>";
    }

    /**
     * Get current directory user
     */
    public function GetUserDirectory($idUser = "") {
        if ($idUser == "") {
            $userId = $_SESSION[md5("Webemyos_User")];
        } else {
            $userId = $idUser;
        }

        $user = new User($this);
        $user->GetById($userId);

        return "../" . $user->Serveur->Value . "/User/" . md5($userId) . "";
    }

    /**
     * Recupere a sucess message
     * */
    function GetMessageValid($id = '') {
        if ($id != '') {
            $id = "id='" . $id . "'";
        }
        return "<span class='FormUserValid' $id>" . $this->GetCode("SaveOk") . "</span>";
    }

    /**
     * Return a error message
     * */
    function GetMessageError($id = '') {
        if ($id != '') {
            $id = "id='" . $id . "'";
        }
        return "<span class='FormUserError'>" . $this->GetCode("Error") . "</span>";
    }
}
