import pygame
import time
import kivy.uix.widget as _kuw
import kivy.graphics.texture as _ktex
import kivy.graphics as _kgr

class PygameSurface:
    def __init__(self, width, height):
        pygame.init()
        self.width = int(width)
        self.height = int(height)
        self.surface = pygame.Surface((self.width, self.height), pygame.SRCALPHA, 32)

class PygameWidget(_kuw.Widget):
    def __init__(self, width=640, height=480, **kwargs):
        super().__init__(**kwargs)
        pygame.init()
        self._w = int(width)
        self._h = int(height)
        self.surface = pygame.Surface((self._w, self._h), pygame.SRCALPHA, 32)
        try:
            self.texture = _ktex.Texture.create(size=(self._w, self._h))
            self.texture.flip_vertical()
        except Exception:
            self.texture = None
        try:
            with self.canvas:
                self.rect = _kgr.Rectangle(texture=self.texture, pos=self.pos, size=(self._w, self._h))
        except Exception:
            self.rect = None
        self.bind(pos=self._update_rect, size=self._update_rect)
    def _update_rect(self, *args):
        try:
            if self.rect is not None:
                self.rect.pos = self.pos
                self.rect.size = self.size
        except Exception:
            pass
    def update(self):
        try:
            raw = pygame.image.tostring(self.surface, 'RGBA')
            if self.texture is not None:
                try:
                    self.texture.blit_buffer(raw, colorfmt='rgba', bufferfmt='ubyte')
                    self.texture.flip_vertical()
                except Exception:
                    try:
                        tmp = self.surface.copy()
                        tmp = pygame.transform.flip(tmp, False, True)
                        raw2 = pygame.image.tostring(tmp, 'RGBA')
                        self.texture.blit_buffer(raw2, colorfmt='rgba', bufferfmt='ubyte')
                    except Exception:
                        pass
        except Exception:
            pass