<?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 pdf
 */
class View_pdf 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('xslt', true);
        $xslt_view_class = Report_config::view_class_name('xslt');
        
        $this->designinfo['add_page_margin'] = true;
        $xslt = new $xslt_view_class($this->viewinfo, $this->file_name, $this->rephead, $this->designinfo, $this->report_id);
        return $xslt->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
