<?php

class CWidgetCustomModule extends CWidgetModule
{
	public $rawData;
	protected $modelObject;
    protected function registerHeaderScripts()
    {
        $class = get_class($this);
        $class = substr($class, strlen('CWidget'));
        $class = strtolower($class);
        $script_path = Yii::getPathofAlias('application.widgets.views.modules.script');
        if (is_file($script_path.DIRECTORY_SEPARATOR.$class.'.php')) {
            include_once $script_path.DIRECTORY_SEPARATOR.$class.'.php';
        }
    }
	public function init()
    {
		$type = strtolower(str_replace('CWidget','',get_class($this)));
		$this->modelObject = ModuleData::model()->find('module_name=:name', array(':name'=>$type));
        if (!isset($this->data)) {
            $this->data = array('data' => array());
            $json_path = Yii::app()->site->model->getFilePath('module_data', $this->page_id, '.json');
            if (file_exists($json_path)) {
                $content = file_get_contents($json_path);
                $this->data = json_decode($content, true);
            }
			

        }
        $data = getIndex($this->data, 'data', array());
		
		if(empty($data)) {
			
			   if(isset($this->rawData)) {
				   $data = ($this->rawData);
			   }
		}
		
        if (!is_array($data) && is_string($data)) {
            $data = json_decode($data, true);
        }
		$this->data['data'] = $data;
        if (!isset($this->page_id) || strlen($this->page_id) == 0) {
            $this->page_id = self::generate_page_id();
        }
        $this->module_data = $data;
        $this->decodeData();
    }
	protected function renderEditTag()
    {
		if (Yii::app()->controller->id == 'builder'  && (Yii::app()->controller->action->id == 'view' || Yii::app()->controller->action->id == 'module')) {
            $data = getIndex($this->data, 'data', array());
            if (is_array($data)) {
                $dstring = json_encode($data);
            } else {
                $dstring = $data;
            }
            echo '<script id="'.$this->page_id.'_data'.'" type="text/json">'.$dstring.'</script>';
			if(isset($this->modelObject)) {
				   echo '<script id="'.$this->page_id.'_view'.'" type="text/json">'.$this->render($this->data['type'],array(), true).'</script>';
			   }
            
        }
    }
	public function renderBody()
    {
		$type = strtolower(str_replace('CWidget','',get_class($this)));
		//echo $type;
        Yii::app()->twigRenderer->renderFile($this, $type.'.php', $this->module_data, false);
    }
}
