# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle


class SelectPoint(object):
    def __init__(self):
        self.point = ()

    def getCoord(self, img):
        fig = plt.figure()
        fig.add_subplot(111)
        plt.imshow(img)
        fig.canvas.mpl_connect('button_press_event', self.onpress)
        plt.show()
        return self.point

    def onpress(self, click):
        self.point = (int(click.xdata), int(click.ydata))
        plt.close(1)
        return self.point


class SelectRect(object):
    def __init__(self):
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)
        self.rect = Rectangle((0, 0), 1, 1, facecolor='None', edgecolor='red')
        self.ax.add_patch(self.rect)
        self.fig.canvas.mpl_connect('button_press_event', self.on_press)
        self.fig.canvas.mpl_connect('button_release_event', self.on_release)

    def getCoord(self, img):
        plt.imshow(img)
        plt.show()
        return int(self.x0), int(self.y0), int(self.x1), int(self.y1)

    def on_press(self, event):
        self.x0 = event.xdata
        self.y0 = event.ydata
        self.x1 = event.xdata
        self.y1 = event.ydata
        self.rect.set_width(self.x1 - self.x0)
        self.rect.set_height(self.y1 - self.y0)
        self.rect.set_xy((self.x0, self.y0))
        self.fig.canvas.draw()
        self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion)

    def on_motion(self, event):
        if self.on_press is True:
            return
        self.x1 = event.xdata
        self.y1 = event.ydata
        self.rect.set_width(self.x1 - self.x0)
        self.rect.set_height(self.y1 - self.y0)
        self.rect.set_xy((self.x0, self.y0))
        self.fig.canvas.draw()

    def on_release(self, event):
        self.x1 = event.xdata
        self.y1 = event.ydata
        self.rect.set_width(self.x1 - self.x0)
        self.rect.set_height(self.y1 - self.y0)
        self.rect.set_xy((self.x0, self.y0))
        self.ax.figure.canvas.draw()
        plt.close(1)


