#!/usr/bin/python3
# coding=utf-8
#
# build.py - Font Builder
# Danial Behzadi<dani.behzi@ubuntu.com>, 2023.
"""
This is a short and cripple edition of Amiri font build utility
To see the whole and compelete version, please refer
https://github.com/alif-type/amiri
"""

import os
import sys
import getopt
import fontforge


def validate_glyphs(font):
    """
    Fixes some common FontForge validation warnings, currently handles:
      * wrong direction
      * flipped references
    """
    wrong_dir = 0x8
    flipped_ref = 0x10
    for glyph in font.glyphs():
        state = glyph.validate(True)
        if state & flipped_ref:
            glyph.unlinkRef()
            glyph.correctDirection()
        if state & wrong_dir:
            glyph.correctDirection()


def generate_font(font, outfile):
    """
    Generates font
    """
    flags = "opentype"
    font.selection.all()
    font.correctReferences()
    font.selection.none()

    # fix some common font issues
    validate_glyphs(font)

    font.generate(outfile, flags=flags)


def make(infile, outfile, latinfile, latincopyright):
    """
    Make font
    """
    font = fontforge.open(infile)
    font.encoding = "Unicode"  # avoid a crash if compact was set

    # sample text to be used by font viewers
    sample = "این مثالی برای نمایش قلم است."

    for lang in ("Arabic (Egypt)", "English (US)"):
        font.appendSFNTName(lang, "Sample Text", sample)

    if latinfile:
        font.mergeFonts(latinfile)

    if latincopyright:
        font.copyright += "\n" + latincopyright

    # Changing font name to make all versions installable
    # together not overwriting each other
    if not latinfile:
        tail = "WOL"
    font.fontname = font.fontname + "-" + tail
    font.familyname = font.familyname + " " + tail
    font.fullname = font.fullname + " " + tail
    for row in font.sfnt_names:
        if row[1] == "UniqueID":
            font.appendSFNTName(row[0], row[1], row[2] + " " + tail)
        if row[1] == "Preferred Family":
            font.appendSFNTName(row[0], row[1], row[2] + " " + tail)

    generate_font(font, outfile)


def usage(extramessage, code):
    """
    Usage
    """
    if extramessage:
        print(extramessage)

    message = f"""Usage: {os.path.basename(sys.argv[0])} OPTIONS...

Options:
  --input=FILE          file name of input font
  --output=FILE         file name of output font
  --latin=FILE          file name of latin font

  -h, --help            print this message and exit
"""

    print(message)
    sys.exit(code)


if __name__ == "__main__":
    try:
        opts, args = getopt.gnu_getopt(
            sys.argv[1:],
            "h",
            [
                "help",
                "input=",
                "output=",
                "latin=",
                "latin-copyright=",
            ],
        )
    except getopt.GetoptError as err:
        usage(str(err), -1)

    INFILE = None
    OUTFILE = None
    LATINFILE = None
    LATINCOPYRIGHT = None

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage("", 0)
        elif opt == "--input":
            INFILE = arg
        elif opt == "--output":
            OUTFILE = arg
        elif opt == "--latin":
            LATINFILE = arg
        elif opt == "--latin-copyright":
            LATINCOPYRIGHT = arg

    if not INFILE:
        usage("No input file specified", -1)
    if not OUTFILE:
        usage("No output file specified", -1)

    make(INFILE, OUTFILE, LATINFILE, LATINCOPYRIGHT)
