# Select tool
#
# Copyright (C) 2009 David Vrabel

class SelectTool(WhiteboardTool):
    def __init__ (self, whiteboard):
        self.whiteboard = whiteboard
        self.selected = None
        self.dragging = None

    def on_left_down(self, pos):
        hit = self.whiteboard.layers['whiteboard'].hit_test_lines(pos)
        if hit:
            self.select(hit)
        else:
            self.deselect()
            hit = self.whiteboard.layers['whiteboard'].hit_test_text(pos, dc)
            if hit:
                self.select(hit)
            else:
                self.deselect()
        self.last_pos = pos

    def on_left_up(self, pos):
        if self.dragging:
            self.update_object(self.dragging)
            self.dragging = False

    def on_motion(self, evt, pos):
        if not self.selected:
            return
        if evt.m_leftDown and self.selected:
            self.dragging = self.selected
            self.dragging.move(pos - self.last_pos)
            self.last_pos = pos
            self.whiteboard.Refresh()

    def select(self, hit):
        if self.selected == hit:
            return;
        if self.selected:
            self.selected.highlight(False)
        self.selected = hit
        self.selected.highlight(True)
        self.whiteboard.Refresh(True)

    def deselect(self):
        if self.selected:
            self.selected.highlight(False)
            self.selected = None
            self.whiteboard.Refresh(True)

    def update_object(self, obj):
        xml_str = "<map><whiteboard>"
        xml_str += obj.toxml('update')
        xml_str += "</whiteboard></map>"

        self.whiteboard.frame.session.send(xml_str)
        self.whiteboard.Refresh(False)
