#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import,
                        print_function)

__license__   = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'

from calibre.customize import ViewerPlugin

JS = '''
function jaxit() {
    var base = %s;
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.src = "file://" + base + "/MathJax.js";

    var config = 'MathJax.Hub.Config({' +
                 'extensions: ["tex2jax.js"],' +
                 'jax: ["input/TeX","output/SVG"]' +
               '});' +
               'MathJax.Hub.Startup.onload();';

    s.text = config;
    document.head.appendChild(s);

}
jaxit();
'''
class MathJax(ViewerPlugin):

    name                = 'MathJax Plugin' # Name of the plugin
    description         = 'Enable viewing of MathJax HTML in the viewer'
    supported_platforms = ['windows', 'osx', 'linux'] # Platforms this plugin will run on
    author              = 'Kovid Goyal' # The author of this plugin
    version             = (1, 0, 0)   # The version number of this plugin
    minimum_calibre_version = (0, 8, 65)

    def load_fonts(self):
        import zipfile
        from calibre.ptempfile import PersistentTemporaryDirectory
        self.mathjax_dir = PersistentTemporaryDirectory('_mathjax')
        with zipfile.ZipFile(self.plugin_path, 'r') as zf:
            zf.extractall(self.mathjax_dir)

    def run_javascript(self, evaljs):
        import json, os
        base = json.dumps(self.mathjax_dir.replace(os.sep, '/'), ensure_ascii=False)
        evaljs(JS%base)

