from django.conf import settings
from django.conf.settings import TEMPLATE_DIRS, TEMPLATE_FILE_EXTENSION
from django.core.template import TemplateDoesNotExist
import sys
import os
from popen2 import popen2

_getdefault = settings.__dict__.get

## these should be set in the settings.py file
PHP_BIN = _getdefault('PHP_BIN', '/usr/bin/php')
PHP_TEMPLATE_FILE_EXTENSION = _getdefault('PHP_TEMPLATE_FILE_EXTENSION', '.php')
PHP_TEMPLATE_DIRS = _getdefault('PHP_TEMPLATE_DIRS', ())

POPEN2_BUFFER_SIZE = _getdefault('POPEN2_BUFFER_SIZE',
                                 sys.platform == 'win32' and -1 or 4096)

auto_tags=(
    'MAINHEADER',
    'MAINFOOTER',
    'MAINBODY',
)

## *sigh* there are no php comment wrappers around this stuff, well there is a
## start but no end.
custom=(
    ("<!--HeaderText-->",
     """<!--HeaderText--><!--{% block MAINCSSLINK %}--><!--{% endblock %}-->
    """),
    ("<title>", "<title>{% block MAINTITLE %}"),
    ("</title>", "{% endblock %}</title>"),
)

tagsets = list(custom)
for tag in auto_tags:
    tagsets.extend((("<!--%s-->" % tag, "<!--{%% block %s %%}-->" %tag),
                    ("<!--/%s-->" %tag, "<!--{% endblock %}-->" )))

tagsets = tuple(tagsets)

def get_template_sources(template_name, template_dirs=None):
    if not template_dirs:
        template_dirs = PHP_TEMPLATE_DIRS
    for template_dir in template_dirs:
        yield os.path.join(template_dir, template_name) + PHP_TEMPLATE_FILE_EXTENSION

def get_php_template(template_name, template_dirs=None):
    tried = []
    for filepath in get_template_sources(template_name, template_dirs):
        if os.path.exists(filepath):
            return filepath
        else:
            tried.append(filepath)
    if template_dirs:
        error_msg = "Tried %s" % tried
    else:
        error_msg = "Your PHP_TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory."
    raise TemplateDoesNotExist, error_msg

def load_php_template_source(template_name, template_dirs=None):
    ## all php template requests must start with 'php:' to keep namespaces
    ## distinct and as an added security measure
    if len(template_name) <= 4 or template_name[:4] != 'php:':
        raise TemplateDoesNotExist, "Not a PHP template request: %s" % template_name
    ## this may also raise a TemplateDoesNotExist exception
    template = get_php_template(template_name[4:], template_dirs)

    ## run php and get the output (should we handle errors? how?
    fdin, fdout = popen2('%s %s' % (PHP_BIN, template), POPEN2_BUFFER_SIZE, mode='b')
    fdout.close()
    page = fdin.read()
    page = page.split('\r\n\r\n', 1)[1]
    fdin.close()
    ## replace php tag with django tag
    for phptag, djtag in tagsets:
        page = page.replace(phptag, djtag, 1)
    return (page, template)
load_php_template_source.is_usable=True
