<?php
/**
 * CodeIgniter report view
 *
 * @category CodeIgniter
 * @license /_licenses/untermStrich/agb_normal.pdf
 * @author Christian Koller
 * @copyright 2009 untermStrich
 * @package views
 * @version $Id$
*/

if (!defined('BASEPATH')) { exit('No direct script access allowed'); }

require_once APPPATH.'us_libraries/US_report_view_result.php';

/**
 * A view for smarty to pdf
 */
class View_smartypdf extends US_report_view_result
{
    
    /**
     * Process the report based on the view mode
     *
     * @param   integer $mode   One of the US_report_view_result::M_... modes
     * @return  mixed   Either void or the filename
     *
     * @see US_report_view_result::M_DIRECT
     * @see US_report_view_result::M_FILE
     */
    protected function process($mode)
    {
        $file_name_html = $this->_create_html();

        $processor = $this->_factory_processor($mode);

        return $processor->process($mode, $this->viewinfo, $file_name_html, $this->rephead, $this->designinfo);
    }

    /**
     * Create the html base file
     *
     * @return  string  The filename
     */
    private function _create_html()
    {
        require_once Report_config::view_file_name('smarty', true);
        $smarty_view_class = Report_config::view_class_name('smarty');
        
        $this->designinfo['add_page_margin'] = true;
        $smarty = new $smarty_view_class($this->viewinfo, $this->file_name, $this->rephead, $this->designinfo, $this->report_id);
        return $smarty->file();
    }

    /**
     * Loads an appropriate pdf processer
     *
     * @param   integer $mode   One of the My_controller::m_... modes
     * @return  View_pdf_processor
     */
    private function _factory_processor($mode)
    {
        $this->CI->load->helper('directory');
        $files = directory_map(APPPATH.'views/Reports/pdf/', true, true);

        $file_size = filesize($this->file_name);

        foreach ($files as $file) {
            if ($file==='Builtin.php') continue; //Builtin is the fallback
            if (strpos($file, EXT)===false) continue; //Onyl accept php files

            require_once APPPATH.'views/Reports/pdf/'.$file;
            $class_name = 'Pdf_'.strtolower(str_replace(EXT, '', $file));
            $class = new $class_name();

            if ($class->is_useable($mode, $file_size)) {
                return $class;
            }
        }

        require_once APPPATH.'views/Reports/pdf/Builtin.php';
        return new Pdf_builtin();
    }

} // END class View_pdf
