#! /usr/bin/env python

from __future__ import division
import sys
import getopt
import codecs
import re
import os
from fontTools import subset, compare, treeshake
from fontTools.misc.captureOutput import captureOutput
from fontTools.misc.inputParsing import getCharListFromInput
from fontTools.misc.util import makeArgs, makeOutputFileName
from fontTools.ttLib import TTFont
from os import rename, listdir
from cStringIO import StringIO

def usage():
    print("usage: runStats inputFile")
    sys.exit(1)        


def treeShake(fontFile):
    args = makeArgs(fontFile)
    with captureOutput():
        treeshake.main(args)         

    reducedFontFile = 'Reduced'+fontFile
    return reducedFontFile

def generateStats(stats):

    target = open("generalStats", 'w')
    target.truncate()

    currentDir = os.getcwd()

    origReduction = []
    tsReduction = []

    template = "{0:25}  {1:10} {2:30}"

    for info in stats:

        target.write(info[0]+" Analysis over\n")
        target.write(info[1])
        target.write("\n\n")
        target.write(template.format("Original font file size:", "{:,}".format(info[2]), "")+"\n")
        reduction = ((info[2] - info[3])*100)/info[2]
        origReduction.append(reduction)
        target.write(template.format("Size after tree-shaking:", "{:,}".format(info[3]), "(Reduction of %.2f%%)" % reduction )+"\n")
        target.write("\n")
        target.write(template.format("Subsetted font file size:", "{:,}".format(info[4]), "")+"\n")
        reduction = ((info[4] - info[5])*100)/info[4]
        tsReduction.append(reduction)
        target.write(template.format("Size after tree-shaking:", "{:,}".format(info[5]), "(Reduction of %.2f%%)" % reduction )+"\n")
        target.write("\n\n")

    target.close()

    target = open("averageStats", 'w')
    target.truncate()
    averageReduction = sum(origReduction)/len(origReduction)
    averageSubsetReduction =  sum(tsReduction)/len(tsReduction)

    target.write("============================================================\n")
    target.write("                            STATS                           \n")
    target.write("============================================================\n")

    target.write("Testing tree shake for {} fonts: \n\n".format(len(stats)))
    target.write("Average size reduction for whole fonts: {:.2f}%\n".format(averageReduction))
    target.write("Average size reduction for subsetted fonts: {:.2f}%\n\n".format(averageSubsetReduction))

    target.write("============================================================\n")
    target.write("                        SAMPLE RESULT                       \n")
    target.write("============================================================\n")
    target.write(stats[0][0]+" Analysis over\n")
    target.write(stats[0][1])
    target.write("\n\n")
    target.write(template.format("Original font file size:", "{:,}".format(stats[0][2]), "")+"\n")
    reduction = ((stats[0][2] - stats[0][3])*100)/stats[0][2]
    origReduction.append(reduction)
    target.write(template.format("Size after tree-shaking:", "{:,}".format(stats[0][3]), "(Reduction of %.2f%%)" % reduction )+"\n")
    target.write("\n")
    target.write(template.format("Subsetted font file size:", "{:,}".format(stats[0][4]), "")+"\n")
    reduction = ((stats[0][4] - stats[0][5])*100)/stats[0][4]
    tsReduction.append(reduction)
    target.write(template.format("Size after tree-shaking:", "{:,}".format(stats[0][5]), "(Reduction of %.2f%%)" % reduction )+"\n")
    target.write("\n\n")

    target.close()
                             

def main(args):

    if len(args) > 0:
        with open(args[0], "r") as file:
            testSuite = []
            for nl, line in enumerate(file):
               try:
                    font, glyphs = line.split()
                    testSuite.append((font, glyphs, 'utf-8'))
               except:
                    font, glyphs, encoding = line.split()
                    testSuite.append((font, glyphs, encoding))
    else:
        usage()
    
    results = []
    for fontFile, inputFile, encoding in testSuite:
        tsFontFile = treeShake(fontFile) 
        charList = getCharListFromInput(inputFile, encoding)
        glyphs = "--text="+''.join(charList)

        filesBefore = listdir(".")
        args = makeArgs(fontFile, glyphs)
        with captureOutput():
            subset.main(args)
        filesAfter = listdir(".")

        #tries to identifiy a new file created in the current folder
        #if fail, assumes that a file with the same name was already there 
        try:
            createdFile = [item for item in filesAfter if item not in filesBefore][0]
        except:
            createdFile = fontFile+'.subset'

        subsetFontFile = makeOutputFileName('Subset'+fontFile, '.ttf')
        rename(createdFile, subsetFontFile)
        tsSubsetFile = treeShake(subsetFontFile) 

        currentDir = os.getcwd()
        origSize = os.path.getsize(currentDir+"/"+fontFile)
        origTsSize = os.path.getsize(currentDir+"/"+tsFontFile)
        subsSize = os.path.getsize(currentDir+"/"+subsetFontFile)
        subsTsSize = os.path.getsize(currentDir+"/"+tsSubsetFile)

        results.append([fontFile, inputFile, origSize, origTsSize, subsSize, subsTsSize])

        os.remove(tsFontFile)
        os.remove(subsetFontFile)
        os.remove(tsSubsetFile)
    generateStats(results)

if __name__ == '__main__':
  main(sys.argv[1:])
