"""
Rectangle  class

Medical Images 2022-23 MUEI/MNUR ETSEIB
D. Tost
"""

from point import Point


class Rectangle:
    @classmethod
    def from_dict(cls, dic):
        color = tuple(dic["color"])
        width = dic["width"]
        height = dic["height"]
        center = Point.from_dict(dic["center"])
        return cls(center, width, height, color)

    def __init__(self, center, width, height, color):
        self.center = center
        self.width = width
        self.height = height
        self.color = color

    def __str__(self):
        return "Rectangle center is {}, width is {}, height is {}".format(
            str(self.center), self.width, self.height
        )

    def __eq__(self, other):
        return self.center == other.center and self.width == other.width and self.height == other.height
    
    def to_dict(self):
        return {
            "center": self.center.to_dict(),
            "width": self.width,
            "height": self.height,
            "color": list(self.color),
        }

    def vmin(self):
        """
        returns the coordinates of the vertex with lowest coordinates of self
        """
        return Point(self.center.x - self.width/2, self.center.y - self.height/2)

    def vmax(self):
        """
        returns the coordinates of the vertex with highest coordinates of self
        """
        return Point(self.center.x + self.width/2, self.center.y + self.height/2)

    def aspect_ratio(self):
        """
        returns the width divided by the height
        """
        return self.width/self.height

    def viewport_transform(self, width, height):
        """
        Returns a transformation matrix that represents the geometric transformation of rasterization
        of self into a viewport of the given width and height
        """
        sx = width / self.width
        sy = -height / self.height
        pmin = self.vmin()
        tx = -sx * pmin.x
        ty = height - sy * pmin.y
        return [[sx, 0, tx], [sy, 0, ty], [0, 0, 1]]

    def fitting_window(self, asp):
        """
        To be implemented.
        Given an aspect ratio it returns the smallest possible centered rectangle
        that encloses self but fits the aspect ratio. To do so, it adds margins
        at top and bottom or right and left to get the desired aspect ratio
        """
        pass


    def rasterization(self, matx):
        """
        To be implemented: it returns a list of 2D points corresponding to the
        rasterization of the rectangle having applied the window-to -viewport transformation matrix matx
        """
        return None
