#!/usr/bin/env python
import Tkinter as tk
from ninepatch import Ninepatch, ScaleError
from PIL import ImageTk
import argparse
import pkg_resources

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Interactively scale Android style 9-patch images.')
    parser.add_argument('image_filename', nargs='?', default='DEMO_IMAGE')
    args = parser.parse_args()

    if args.image_filename == 'DEMO_IMAGE':
        args.image_filename = pkg_resources.resource_stream('ninepatch', 'data/ninepatch_bubble.png')

    ninepatch = Ninepatch(args.image_filename)

    img = None

    border = 20

    def resize(event):
        global img
        root.title(title)
        try:
            scaled_image = ninepatch.render(event.width - border * 2, event.height - border * 2)
            img = ImageTk.PhotoImage(scaled_image)
            canvas.delete("all")
            canvas.create_image(border, border, anchor=tk.NW, image=img)
            if ninepatch.fill_area:
                canvas.create_rectangle((
                    border + ninepatch.fill_area[0][0],
                    border + ninepatch.fill_area[0][1],
                    event.width - border - ninepatch.fill_area[1][0],
                    event.height - border - ninepatch.fill_area[1][1],
                ), dash=(3, 6), outline='black')
        except ScaleError, e:
            root.title(e)

    title = '9-patch viewer'

    root = tk.Tk()
    root.title(title)

    root.bind('<Escape>', lambda e: root.destroy())

    canvas = tk.Canvas(root, width=int(ninepatch.image.size[0] * 1.5), height=int(ninepatch.image.size[1] * 1.5), bg='#BBB')
    canvas.pack(fill=tk.BOTH, expand=tk.YES)
    canvas.bind('<Configure>', resize)

    root.mainloop()
