<?php

namespace Velis\Mvc\View;

use Smarty_Internal_Template;
use Smarty_Resource_Custom;
use Smarty_Template_Source;
use SmartyException;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class SmartyResourceIoncube extends Smarty_Resource_Custom
{
    /**
     * {@inheritDoc}
     */
    public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
    {
        $source->filepath = $this->buildFilepath($source, $_template);
        $source->uid = sha1($source->type . ':' . $source->filepath);
        $mtime = $this->fetchTimestamp($source->name);

        if ($mtime !== null) {
            $source->timestamp = $mtime;
        } else {
            $this->fetch($source->filepath, $content, $timestamp);
            $source->timestamp = isset($timestamp) ? $timestamp : false;
            if (isset($content)) {
                $source->content = $content;
            }
        }

        $source->exists = !!$source->timestamp;
    }

    /**
     * build template filepath by traversing the template_dir array
     *
     * @param Smarty_Template_Source   $source    source object
     * @param Smarty_Internal_Template $_template template object
     *
     * @return string fully qualified filepath
     * @throws SmartyException
     */
    protected function buildFilepath(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
    {
        $file = $source->name;
        // absolute file ?
        if ($file[ 0 ] === '/' || $file[ 1 ] === ':') {
            $file = $source->smarty->_realpath($file, true);
            return is_file($file) ? $file : false;
        }
        // go relative to a given template?
        if (
            $file[ 0 ] === '.' && $_template && $_template->_isSubTpl()
            && preg_match('#^[.]{1,2}[\\\/]#', $file)
        ) {
            if (
                $_template->parent->source->type !== 'file' && $_template->parent->source->type !== 'extends'
                && !isset($_template->parent->_cache[ 'allow_relative_path' ])
            ) {
                throw new SmartyException("Template '{$file}' cannot be relative to template of resource type '{$_template->parent->source->type}'");
            }
            // normalize path
            $path =
                $source->smarty->_realpath(dirname($_template->parent->source->filepath) . DIRECTORY_SEPARATOR . $file);
            // files relative to a template only get one shot
            return is_file($path) ? $path : false;
        }
        // normalize DIRECTORY_SEPARATOR
        if (strpos($file, DIRECTORY_SEPARATOR === '/' ? '\\' : '/') !== false) {
            $file = str_replace(DIRECTORY_SEPARATOR === '/' ? '\\' : '/', DIRECTORY_SEPARATOR, $file);
        }
        $_directories = $source->smarty->getTemplateDir(null, $source->isConfig);
        // template_dir index?
        if ($file[ 0 ] === '[' && preg_match('#^\[([^\]]+)\](.+)$#', $file, $fileMatch)) {
            $file = $fileMatch[ 2 ];
            $_indices = explode(',', $fileMatch[ 1 ]);
            $_index_dirs = array();
            foreach ($_indices as $index) {
                $index = trim($index);
                // try string indexes
                if (isset($_directories[ $index ])) {
                    $_index_dirs[] = $_directories[ $index ];
                } elseif (is_numeric($index)) {
                    // try numeric index
                    $index = (int)$index;
                    if (isset($_directories[ $index ])) {
                        $_index_dirs[] = $_directories[ $index ];
                    } else {
                        // try at location index
                        $keys = array_keys($_directories);
                        if (isset($_directories[ $keys[ $index ] ])) {
                            $_index_dirs[] = $_directories[ $keys[ $index ] ];
                        }
                    }
                }
            }
            if (empty($_index_dirs)) {
                // index not found
                return false;
            } else {
                $_directories = $_index_dirs;
            }
        }
        // relative file name?
        foreach ($_directories as $_directory) {
            $path = $_directory . $file;
            if (is_file($path)) {
                return (strpos($path, '.' . DIRECTORY_SEPARATOR) !== false) ? $source->smarty->_realpath($path) : $path;
            }
        }
        if (!isset($_index_dirs)) {
            // Could be relative to cwd
            $path = $source->smarty->_realpath($file, true);
            if (is_file($path)) {
                return $path;
            }
        }
        // Use include path ?
        if ($source->smarty->use_include_path) {
            return $source->smarty->ext->_getIncludePath->getIncludePath($_directories, $file, $source->smarty);
        }

        return false;
    }

    /**
     * @param string $name
     * @param string $source
     * @param int    $mtime
     */
    protected function fetch($name, &$source, &$mtime)
    {
        if (file_exists($name)) {
            if (function_exists('ioncube_read_file')) {
                $source = ioncube_read_file($name);
            } else {
                $source = file_get_contents($name);
            }

            $mtime = filemtime($name);
        }
    }
}
