<?php
/**
 * User: David Camacho
 * Date: 31/03/2015
 * Time: 18:04
 */

include_once "./classes/User.php";

class ModuleController {
    var $langs;
    var $name;
    var $user;

    protected function init(){

        $this->user = new User();

        // Load languages
        if (!isset($_SESSION["lang"]))
            $_SESSION["lang"] = _lang;

        // Add translation files
        if ($this->user->getRole() == 0)      // Student Modules
            include_once './modules/student/' . $this->name . "/translates/" . $_SESSION["lang"] . "/translate.php";
        elseif ($this->user->getRole() == 1)  // Teacher Modules
            include_once './modules/teacher/' . $this->name . "/translates/" . $_SESSION["lang"] . "/translate.php";

        //Add js files
        $this->addModuleJS();

        $class_name = ucfirst($this->name)."ModuleTranslate";
        $this->langs = new $class_name;
    }

    protected function displayModule($view){
        if ($this->user->getRole() == 0)
            include_once './modules/student/' . $this->name . "/views/". $view . ".html";
        elseif ($this->user->getRole() == 1)
            include_once './modules/teacher/' . $this->name . "/views/". $view . ".html";
    }

    protected function getTranslates($word){
        return $this->langs->getTranslate($word);

    }

    private function addModuleJS(){
        $js = '';
        $handle = '';
        $file = '';
        $role = '';

        if ($this->user->getRole() == 0)
            $role = 'student';
        elseif ($this->user->getRole() == 1)
            $role = 'teacher';

        // open the "js" directory
        if ($handle = opendir('./modules/' . $role . '/'. $this->name .'/js')) {
            // list directory contents
            while (false !== ($file = readdir($handle))) {
                // only grab file names
                if (is_file('./modules/' . $role . '/'. $this->name .'/js/' . $file)) {
                    // insert HTML code for loading Javascript files
                    $js .= '<script src="./modules/' . $role . '/'. $this->name .'/js/' . $file . '" type="text/javascript"></script>' . "\n";
                }
            }
            closedir($handle);
            printf($js);
        }

    }

    protected function destroy(){
        return NULL;
    }
}