#!/usr/bin/python3

import argparse
import logging
import os
import sys

from keyman_config import (
  are_requirements_missing, add_standard_arguments, initialize_logging,
  initialize_sentry, verify_dbus_running)
from keyman_config.kvk2ldml import parse_kvk_file, print_kvk, convert_ldml, output_ldml


def main():
    parser = argparse.ArgumentParser(
        description='Convert a Keyman kvk on-screen keyboard file to an LDML file. Optionally ' +
        'print the details of the kvk file.')
    parser.add_argument('-p', "--print", help='print kvk details', action="store_true")
    parser.add_argument('-k', "--keys", help='if printing also print all keys', action="store_true")
    parser.add_argument('-o', '--output', metavar='LDMLFILE', help='output LDML file location')
    parser.add_argument('kvkfile', help='kvk file')
    add_standard_arguments(parser)

    args = parser.parse_args()

    initialize_logging(args)
    initialize_sentry()
    verify_dbus_running()

    if are_requirements_missing():
        logging.error('km-kvk2ldml: Missing requirements. Please install python3-fonttools.')
        sys.exit(1)

    name, ext = os.path.splitext(args.kvkfile)
    # Check if input file extension is kvk
    if ext != ".kvk":
        logging.error("km-kvk2ldml: error, input file %s is not a kvk file.", args.kvkfile)
        logging.error("km-kvk2ldml [-h] [-k] [-p] [-o <ldml file>] <kvk file>")
        sys.exit(2)

    # Check if input kvk file exists
    if not os.path.isfile(args.kvkfile):
        logging.error("km-kvk2ldml: error, input file %s does not exist.", args.kvkfile)
        logging.error("km-kvk2ldml [-h] [-k] [-p] [-o <ldml file>] <kvk file>")
        sys.exit(2)

    kvkData = parse_kvk_file(args.kvkfile)

    if args.print:
        print_kvk(kvkData, args.keys)

    outputfile = args.output if args.output else f'{name}.ldml'

    dirname = os.path.dirname(outputfile)
    if dirname == '':
        dirname = '.'
    if not os.path.isdir(dirname):
        if os.path.exists(dirname):
            logging.error(f'km-kvk2ldml: error, `{dirname}` exists but is not a directory')
            sys.exit(3)
        os.makedirs(dirname)

    try:
        with open(outputfile, 'wb') as ldmlfile:
            kmpJsonFilename = os.path.join(os.path.dirname(args.kvkfile), 'kmp.json')
            ldml = convert_ldml(name, kvkData, kmpJsonFilename)
            output_ldml(ldmlfile, ldml)
    except PermissionError:
        logging.error(f'km-kvk2ldml: error, permission denied writing file `{outputfile}`')
        sys.exit(4)
    except IsADirectoryError:
        logging.error(f'km-kvk2ldml: error, cannot create file `{outputfile}` - it is a directory')
        sys.exit(5)


if __name__ == "__main__":
    main()
