import os
import tempfile
import subprocess
import base64
import mimetypes

import pkg_resources

# TODO
# use `java -version` to check java version
# or node version?

def get_resource(fpath):
    ''' Get file path from python egg resource
    '''
    return pkg_resources.resource_filename('meteor', fpath)

jar_htmlcompressor = get_resource('bin/htmlcompressor-1.5.3.jar')
jar_yui = get_resource('bin/yuicompressor-2.4.7.jar')
jar_compiler = get_resource('bin/compiler.jar')

def process(cmd, text, shell=False):
    ''' Call subprocess, pass text as stdin, get output from stdout
    '''
    p = subprocess.Popen(cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=shell)

    stdout, stderr = p.communicate(text)

    if stderr and not stdout:
        raise Exception(stderr)

    return stdout

def process2(cmd, out_path):
    ''' Call subprocess, get output from file specified as out_path
    '''
    ret = subprocess.check_output(cmd, shell=True)
    return open(out_path, 'rb').read()

def swapext(fpath, ext):
    ''' Change file extension
    '''
    return fpath[0:fpath.rindex('.')] + ext

class Compiler():

    def __init__(self, src=None, dest=None):
        self.src = src
        self.dest = dest
        self.temp_dir = tempfile.mkdtemp()

    def html_compress(self, content, fpath=None):
        content = process(r'java -jar %s' % jar_htmlcompressor, content)
        if fpath:
            return content, fpath
        else:
            return content

    def css_compress(self, content, fpath=None):
        content = process(r'java -jar %s --type css' % jar_yui, content)
        if fpath:
            return content, fpath
        else:
            return content
   
    def js_compress(self, content, fpath=None):
        content = process(r'java -jar %s' % jar_compiler, content)
        if fpath:
            return content, fpath
        else:
            return content

    def ts_compile(self, content, fpath):
        # this does not work yet
        # print('ts file ', fpath)
        # return content, fpath

        src_path = os.path.join(self.src, fpath)
        dname, fname = os.path.split(fpath)

        fpath = swapext(fpath, '.js')
        out_path = os.path.join(self.temp_dir, fpath) # tsc output file is here

        cmd = r'tsc --module amd --outDir %s %s' % (os.path.join(self.temp_dir, dname), src_path)
        return process2(cmd, out_path), fpath

    def less_compile(self, content, fpath):
        src_path = os.path.join(self.src, fpath)

        dname, fname = os.path.split(fpath)
        out_dir = os.path.join(self.temp_dir, dname)
        os.makedirs(out_dir)       

        fpath = swapext(fpath, '.css')
        out_path = os.path.join(self.temp_dir, fpath)

        cmd = r'lessc %s > %s' % (src_path, out_path)
        return process2(cmd, out_path), fpath

    def base64image(self, content, fpath):
        type = mimetypes.guess_type(fpath)[0]
        return 'data:{};base64,{}'.format(type, base64.b64encode(content).decode('ascii'))

