#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 jem@seethis.link
# Licensed under the MIT license (http://opensource.org/licenses/MIT)

from __future__ import absolute_import, division, print_function, unicode_literals

import tkinter
import argparse
import json

import kle

arg_parser = argparse.ArgumentParser(
    description='KLE test script'
)
arg_parser.add_argument(
    'layout', type=str, action='store',
    help='The layout file to test'
),
arg_parser.add_argument(
    "-m", "--mirror",
    action = 'store_const', const = True, default = False,
    dest = "mirror",
    help = "Mirror the supplied layout",
)

arg_parser.add_argument(
    "-o", "--out-file", type=str,
    help = "The output file to write to.",
)

args = arg_parser.parse_args()

if 0:
    leg1 = "0\n6\n2\n8\n9\nb\n3\n5\n1\n4\n7\na"
    leg2 = "0\n\n\n\n\nb\n3"
    key1 = kle.KLEKey(0, 0, 1, 1, leg1)
    key2 = kle.KLEKey(1, 0, 1, 1, leg2)

    print(key1)
    print(key1.get_legend_list())

    print(key2)
    print(key2.get_legend_list())

def tk_draw_key(can, key, offset):
    verts = key.get_rect_points()
    bb_verts = key.bounding_box_points()

    trans = [(x+offset[0], y+offset[1]) for (x, y) in verts]
    trans_bb = [(x+offset[0], y+offset[1]) for (x, y) in bb_verts]

    # draw the bounding boxes as well
    can.create_polygon(
        trans_bb,
        fill='',
        outline="red",
    )

    # draw the key outlines
    can.create_polygon(
        trans,
        fill=key.properties.bg,
        outline=key.properties.fg
    )

    # draw the center of the keys
    center = key.get_center()
    can.create_text(
        center.x + offset[0], center.y + offset[1],
        text="x"
    )

def tk_draw_layout(keyboard):
    main_win = tkinter.Tk()
    can = tkinter.Canvas(main_win, width=800, height=800)
    main_win.geometry("+400+400")
    main_win.title("kle viewer")
    can.pack()

    min_x = 0
    min_y = 0
    for key in keyboard.get_keys():
        bbox = key.bounding_box_points()
        min_x = min(min_x, *[point.x for point in bbox])
        min_y = min(min_y, *[point.y for point in bbox])


    for key in keyboard.get_keys():
        # draw_key(t, key)
        tk_draw_key(can, key, (-min_x + key.spacing//2, -min_y + key.spacing//2))
    tkinter.mainloop()


keyboard = kle.KLEKeyboard.from_file(args.layout, spacing=50)

if args.mirror:
    keyboard.mirror()

if args.out_file != None:
    with open(args.out_file, 'w') as out_file:
        out_file.write(json.dumps(keyboard.to_json()))

tk_draw_layout(keyboard)
