<?php namespace App\Modules\Utils\Javascript;

use View, Session, Config;
class JavaScript {

	const SESSION_NAME_VARS = 'JSVARS';
	protected $namespace 	= 'inncore';

	/*public function message($message, $type='success')
	{
		$messages = Session::get(static::SESSION_NAME, array());
		$messages[] = compact('message', 'type');
		Session::flash(static::SESSION_NAME, $messages);
	}*/
	public function makeVar($key, $value)
	{
		return "<script>{$this->namespace}.{$key} = {$this->ValueForJavaScript($value)};</script>";
	}

	public function renderVars()
    {
    	$script = '';

        $vars 	= Session::get(static::SESSION_NAME_VARS, array());
        $vars 	= array_merge($vars, Config::get('javascript::default_vars'));

        if (count($vars)>0)
        {
           	Session::flash(static::SESSION_NAME_VARS, array());
			$script.="//Inicializamos el namespace {$this->namespace} \n" ;
			$script.="{$this->namespace} = {};\n" ;
           
           	$script.="//Agregamos variables al namespace {$this->namespace} \n" ;
			foreach ($vars as $var => $val) {
					$script.= $this->createVar($var, $val)."\n";//$var.'='.'"'.$val.'";';
			}
        }

        return '<script>'.$script.'</script>';
    }

    protected function createVar($key, $value)
    {
    	return "{$this->namespace}.{$key} = {$this->ValueForJavaScript($value)};";
    }

	/**
	* Format a value for JavaScript
	*/
	protected function ValueForJavaScript($value)
	{
		$type = gettype($value);
		switch ($type) {
			case 'string':
					return "'{$this->escape($value)}'";
				break;
			case 'array':
					return json_encode($value);
				break;
			case 'integer':
			case 'double':
					return $value;
				break;
			case 'boolean':
					return $value ? 'true' : 'false';
				break;
			case 'object':
					return json_encode($value);
				break;
			case 'NULL':
					return 'null';
				break;
			default:
				break;
		}
	}


	/**
	 * Escapa las comillas
	 */
	protected function escape($value)
    {
        return str_replace("'", "\\'", $value);
    }


	/**
	* Get a bootstrap alert
	*
	* @param string $message Message to show
	* @param string $type Alert type (For example, if you want a "alert-danger", you need put only "danger")
	* @param bool $close Define if you want a close button
	*
	* @return string Html string with the element
	*/
	/*public function make($message, $type='success') {

		$message_html = '';
		if(!is_array($message))
			$message_html =	$message;
		else {
			foreach ($message as $msg) {
				$message_html ='<p>'.$msg.'</p>';
			}
		}
		

		return View::make('alert::alert')
				->with('type', 		$type)
				->with('message', 	$message_html);
	}*/



}