#!/usr/bin/env python3
import dashio
import json
import os
import textwrap
import argparse

def format_c(c64_str: str, width=80) -> str:
    new_l = textwrap.wrap(
        c64_str,
        width=width
    )
    new_s = '"\n"'.join(new_l)
    return '"' + new_s + '"'

def format_python(c64_str: str, width=80) -> str:
    new_l = textwrap.wrap(
        c64_str,
        width=width
    )
    new_s = '"\\\n"'.join(new_l)
    return '"' + new_s + '"'

def parse_commandline_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument('file', help="Input file name.")
    parser.add_argument("-f", "--format", dest="format", default="None", help="Format output. Options: 'None', 'C', 'Python' (Default 'None').")
    parser.add_argument("-o", "--out", dest="out_file", help="output filename.")
    parser.add_argument("-w", "--width", dest="width", default=80, type=int, help="Width of formatted output (Default 80).")
    args = parser.parse_args()
    return args

def main():
    args = parse_commandline_arguments()
    json_filename = args.file
    c64_filename = os.path.splitext(json_filename)[0] + ".c64"
    try:
        with open(json_filename, mode="r") as fp:
            json_cfg = fp.read()

    except FileNotFoundError:
        print("File not found")

    config_dict = json.loads(json_cfg)
    cfg64 = dashio.encode_cfg64(config_dict)
    cfg_file = open(c64_filename, "w")

    out_format = args.format.upper()
    if out_format == 'C':
        cfg_file.write(format_c(cfg64, width=args.width))
    elif out_format == 'PYTHON':
        cfg_file.write(format_python(cfg64, width=args.width))
    else:
        cfg_file.write(cfg64)

    cfg_file.close()


if __name__ == "__main__":
    main()
