#!/usr/bin/env python3
# coding=utf8

import sys
import os
import re
import subprocess
import fontforge

# Double-quotes required here, for version-bump.sh:
# version-bump.sh is not working here, need to adjust manually!
version = "3.2.0"

fa_version = '6.5.1'
archive = 'fontawesome-free-{}-desktop.zip'.format(fa_version)

vectorsdir = 'svgs'
fontdir = '.'
fontfile = 'FontAwesome.otf'
glyphsetfile = 'i_fa.sh'
glyphsetsdir = '../../../bin/scripts/lib'

def addIcon(codepoint, name, filename):
    """ Add one outline file and rescale/move """
    filename = os.path.join(vectorsdir, filename)
    glyph = font.createChar(codepoint, name)
    glyph.importOutlines(filename)
    xmin, ymin, xmax, ymax = glyph.boundingBox()
    glyph.width = int(xmax + xmin) # make left and right bearings equal
    glyph.manualHints = True

def createGlyphInfo(icon_datasets, filepathname, into):
    """ Write the glyphinfo file """
    with open(filepathname, 'w', encoding = 'utf8') as f:
        f.write(u'#!/usr/bin/env bash\n')
        f.write(intro)
        f.write(u'# Script Version: (autogenerated)\n')
        f.write(u'test -n "$__i_fa_loaded" && return || __i_fa_loaded=1\n')
        for _, codepoint, _, *name in icon_datasets:
            codepoint = int(codepoint, 16)
            f.write(u"i='{}' i_fa_{}=$i\n".format(chr(codepoint), name[0]))
            for more_names in name[1:]:
                f.write(u"      i_fa_{}=$i\n".format(more_names))
        f.write(u'unset i\n')

print('\nReading mapping file')
mapping = []
with open('mapping', 'r') as f:
    for line in f.readlines():
        line = line.strip()
        if line.startswith('#') or len(line) < 1:
            continue
        mapping.append(tuple(re.split(' +', line.strip())))
print('Found {} entries'.format(len(mapping)))
mapping.sort(key=(lambda x: x[1]))

print('Fetching Font Awesome archive "{}"\n'.format(archive))
if subprocess.call('curl -OL https://github.com/FortAwesome/Font-Awesome/releases/download/' + fa_version + '/' + archive, shell=True):
    sys.exit('Error fetching Font Awesome archive')
print('\nUnpacking Font Awesome archive')
if subprocess.call('rm -rf svgs fontawesome-free-*-desktop && unzip -q *.zip && mv fontawesome-free-*-desktop/svgs . && rm -rf fontawesome-free-*-desktop.zip', shell=True):
    sys.exit('Error unpacking archive')

svg_dirs = os.listdir(vectorsdir)
svgs = []
for d in svg_dirs:
    svgs += os.listdir(vectorsdir + '/' + d)
print('Found {} svgs'.format(len(svgs)))

font = fontforge.font()
font.fontname = 'FA-NerdFont-Regular'
font.fullname = 'FA Nerd Font Regular'
font.familyname = 'FA Nerd Font'
font.ascent = 1000
font.descent = 200
font.encoding = 'UnicodeFull'

# Add valid space glyph to avoid "unknown character" box on IE11
glyph = font.createChar(32)
glyph.width = 200

font.sfntRevision = None # Auto-set (refreshed) by fontforge
font.version = version
font.copyright = 'Fonticons, Inc'
font.appendSFNTName('English (US)', 'Version', archive + '; ' + version)
font.appendSFNTName('English (US)', 'Vendor URL', 'https://github.com/ryanoasis/nerd-fonts')
font.appendSFNTName('English (US)', 'Copyright', 'Fonticons, Inc')

for _, codepoint, file, *names in mapping:
    codepoint = int(codepoint, 16)
    addIcon(codepoint, names[0], file)

num_icons = len(mapping)

print('Generating {} with {} glyphs'.format(fontfile, num_icons))
font.ascent = 1050
font.descent = 250
font.generate(os.path.join(fontdir, fontfile), flags=("no-FFTM-table",))

codepoints = [ int(p, 16) for _, p, *_ in mapping ]
aliases = [ len(n) - 1 for _, _, _, *n in mapping ]
intro  = u'# Font Awesome (version {}, {} icons, {} aliases)\n'.format(fa_version, num_icons, sum(aliases))
intro += u'# Does not include all icons of the release\n'
intro += u'# Codepoints: {:X}-{:X} with gaps\n'.format(min(codepoints), max(codepoints))
intro += u'# Nerd Fonts Version: {}\n'.format(version)

print('Generating GlyphInfo {}'.format(glyphsetfile))
createGlyphInfo(mapping, os.path.join(glyphsetsdir, glyphsetfile), intro)
print('Finished')
