# -*- coding: utf-8 -*-

from pelican import signals
from subprocess import call
import logging
import os

logger = logging.getLogger(__name__)

# Display command output on DEBUG and TRACE
SHOW_OUTPUT = logger.getEffectiveLevel() <= logging.DEBUG
PATH_CSS = 'output/theme/css/'
PATH_JS = 'output/theme/js/'

"""
Minify CSS and JS files in output path
with css-html-js-minify.
"""


def minify(pelican):
    """
      Minify CSS and JavaScript
      :param pelican: The Pelican instance
    """
    for dirpathcss, _, filenames in os.walk(PATH_CSS):
        for name in filenames:
            if os.path.splitext(name)[1] in '.css':
                filepath = os.path.join(dirpathcss, name)
                logger.info('minifiy %s with css-html-js-minify', filepath)
                call('css-html-js-minify {}'.format(filepath),
                     shell=True)

    for dirpathjs, _, filenames in os.walk(PATH_JS):
        for name in filenames:
            if os.path.splitext(name)[1] in '.js':
                filepath = os.path.join(dirpathjs, name)
                logger.info('minifiy %s with css-html-js-minify', filepath)
                call("css-html-js-minify {}".format(filepath),
                     shell=True)


def register():
    signals.finalized.connect(minify)
