#
#  BlobEdit - A totally silly application for showing
#  ========   off the GUI framework and providing an example
#             of its use.
#
#  Blobs are red squares that you place on a Blob Document
#  by clicking and move around by dragging. You can save
#  your blob arrangement in a file and load it back later
#  to impress your friends (or send them away screaming).
#

import pickle
from GUI import Application, View, Document, Window, ScrollFrame, rgb
from GUI.Geometry import pt_in_rect, offset_rect
from GUI.StdColors import black, red


class BlobApp(Application):

    def __init__(self):
        Application.__init__(self)
        self.new_cmd()

    def make_new_document(self):
        return BlobDoc()

    def make_file_document(self, fileref):
        return BlobDoc()

    def make_window(self, document):
        win = Window(size = (400, 400), document = document)
        view = BlobView(model = document, extent = (0, 0, 1000, 1000))
        frame = ScrollFrame(view)
        win.place(frame, left = 0, top = 0, right = 0, bottom = 0, sticky = 'nsew')
        win.show()


class BlobView(View):

    def draw(self, canvas):
        for blob in self.model.blobs:
            blob.draw(canvas)

    def mouse_down(self, event):
        x, y = event.position
        for blob in self.model.blobs:
            if blob.contains(x, y):
                self.drag_blob(blob, x, y)
                return
        self.model.add_blob(Blob(x, y))

    def drag_blob(self, blob, x0, y0):
        for event in self.track_mouse():
            x, y = event.position
            self.model.move_blob(blob, x - x0, y - y0)
            x0 = x
            y0 = y


class BlobDoc(Document):

    blobs = None

    def new_contents(self):
        self.blobs = []

    def read_contents(self, file):
        self.blobs = pickle.load(file)

    def write_contents(self, file):
        pickle.dump(self.blobs, file)

    def add_blob(self, blob):
        self.blobs.append(blob)
        self.changed()
        self.notify_views()

    def move_blob(self, blob, dx, dy):
        blob.move(dx, dy)
        self.changed()
        self.notify_views()


class Blob:

    def __init__(self, x, y):
        self.rect = (x - 20, y - 20, x + 20, y + 20)

    def contains(self, x, y):
        return pt_in_rect((x, y), self.rect)

    def move(self, dx, dy):
        self.rect = offset_rect(self.rect, (dx, dy))

    def draw(self, canvas):
        l, t, r, b = self.rect
        canvas.newpath()
        canvas.moveto(l, t)
        canvas.lineto(r, t)
        canvas.lineto(r, b)
        canvas.lineto(l, b)
        canvas.closepath()
        canvas.forecolor = red
        canvas.fill()
        canvas.forecolor = black
        canvas.stroke()


BlobApp().run()
