import re
import sys

USAGE_MSG = '''
Font converter for jDAAD (A DAAD text adventure engine interpreter in javascript, https://github.com/Utodev/jDAAD) by Alexey Galkin, 2023. MIT license.

Usage:
       python jdaadfc.py <source> <destination> <mode>

Mode:
       ascii   convert font.js to ASCII-font file
       js      convert ASCII-font file to font.js
'''

if len(sys.argv) != 4:
   print(USAGE_MSG)
   quit()

input_filename = sys.argv[1]
output_filename = sys.argv[2]
mode =  sys.argv[3]

output = ''

with open(input_filename, 'r') as file:

   if mode == 'ascii':
           input_file = file.read()
           js_font = input_file[input_file.find('[')+1:input_file.find(']')]
           js_font = js_font.replace('0x', '').split(',')
           for byte in js_font:
               line = bin(int(byte, 16))[2:]
               line = '0' * (8-len(line)) + line
               line = line.replace('0', '.').replace('1', '#')
               output = output + line + '\n'

   elif mode == 'js':
       input_file = file.readlines()
       output = [hex(int(byte.replace('.', '0').replace('#', '1'), 2)) for byte in input_file]
       output = f'''// The DAAD 8x6 font converted by jdaadfc.

var font = [{', '.join(output)}];
                               '''

   else:
           print(USAGE_MSG)
           quit()

with open(output_filename, 'w') as file:
       file.write(output)