from siege.util import PixelVector


class Frame(object):
    def __init__(self, x, y, size=None, origin=None):
        self.x = x
        self.y = y
        self.size = Frame._convert(size)
        self.origin = Frame._convert(origin)

        self.index = -1

    @property
    def width(self):
        return self.size.x

    @property
    def height(self):
        return self.size.y

    @staticmethod
    def _convert(value):
        return value if isinstance(value, PixelVector) or not value else PixelVector(value[0], value[1])


class Frames(object):
    def __init__(self, frames, time=0):
        self.frames = frames
        self.time = time

    def __add__(self, frames):
        return Frames(self.frames + frames)

    def __radd__(self, frames):
        return Frames(frames + self.frames)

    def __iadd__(self, frames):
        self.frames.extend(frames)

    def __call__(self, *args):
        return [self.frames[i - 1] for i in args] if args else self.frames

    def indices(self, *args):
        return [self.frames[i - 1].index for i in args] if args else [frame.index for frame in self.frames]


class SpriteSheet(object):
    def __init__(self):
        self.frames = []

    def get(self, frames, size=None, origin=None):
        origin = origin or PixelVector(0, 0)
        if isinstance(frames, Frame):
            frames = [frames]
        for frame in frames:
            if not frame.size:
                frame.size = Frame._convert(size)
            if not frame.origin:
                frame.origin = Frame._convert(origin)
            frame.index = len(self.frames)
            self.frames.append(frame)
        return Frames(frames)
