<?php

class Output {

    private static $_instance;

    private $view = false;
    protected $values = Array();

    private $_template = '';
    private $_extension = '';
    
    //SINGLETON==============================================
    private function __construct() {
        $this->_template = ( defined('TEMPLATE_DEFAULT') ) ? TEMPLATE_DEFAULT : 'DefaultTemplate';
        $this->_extension = ( defined('TEMPLATE_FILETYPE') ) ? TEMPLATE_FILETYPE : '.mustache';
    }

    private static function newObj() {
        if (!isset(self::$_instance)) {
            self::$_instance = new Output();
        }
        return self::$_instance;
    }

    public function getInstance() {
        if (!isset(self::$_instance)) {
            return self::newObj();
        }
        return self::$_instance;
    }

    public function setTemplate($template = 'DefaultTemplate') {
        $this->_template = $template;
        return $this;
    }

    public static function renderView($name, $values = null, $location = null) {
        if (!$location) {
            $segments = explode('/', debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)[0]['file']);
            array_pop($segments);
            $location = implode('/', $segments) . '/views/';
        }
        
        self::$_instance->setView($name, $values, $location)->render();
    }

    public function setView($name, $values = Array(), $location = null) {
        
        $folder = '';
        if (!$location) {
            $segments = explode('/', debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)[0]['file']);
            array_pop($segments);
            $location = implode('/', $segments) . '/views/';
        }
        $folder = $location;
        $location .= $name;

        if (strpos($this->_extension, $location) == 0) {
            $location .= $this->_extension;
        }

        $this->view = Array();
        $this->view['location'] = $location;
        $this->view['folder'] = $folder;
        $this->view['values'] = $values;
        return $this;
    }

    public function addValue($key, $value){
        $this->view['values'][$key] = $value;
    }

    public function render() {
        if(!is_file(__DIR__."/classes/".strtolower($this->_template)."/".$this->_template.'.php') ){
            $this->_template = 'DefaultTemplate';
        }
        include_once __DIR__."/classes/".strtolower($this->_template)."/".$this->_template.'.php';
        last_class()->setView($this->view)->render();
    }
}
