import os
import platform
import pygame

class DriverException(Exception):
    def __init__(self, driverName):
        self.driverName = driverName

    def __str__(self):
        return repr(self.driverName)

class Screen():
    screen = None
    bgColor = None

    def __init__(self, width, height, fullscreen):
        size = (width, height)

        disp_no = os.getenv('DISPLAY')
        if disp_no:
            print ("I'm running under X display = {0}".format(disp_no))
            self.screen = pygame.display.init()
        else:
            print("Try to run from framebuffer...")
            drivers = ['fbcon','directfb', 'svgalib']

            found = False
            for driver in drivers:
                print(driver)
                if not os.getenv('SDL_VIDEODRIVER'):
                    os.putenv('SDL_VIDEODRIVER', driver)
                try:
                    self.screen = pygame.display.init()
                except pygame.error:
                    print("Driver: {0} failed.".format(driver))
                    continue
                found = True
                break

            if not found:
                raise Exception('No suitable video driver found!')

        self.realSize = (pygame.display.Info().current_w, pygame.display.Info().current_h)
        if size[0] > self.realSize[0]:
            size = (self.realSize[0], size[1])
        if size[1] > self.realSize[1]:
            size = (size[0], self.realSize[1])
        if not fullscreen:
            self.screen = pygame.display.set_mode(size)
        else:
            self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN|pygame.DOUBLEBUF|pygame.HWSURFACE)


    def quit(self):
        pygame.display.quit()

    def update(self):
        pygame.display.flip()

    def blit(self, surface, x, y):

        self.screen.blit( surface, (x, y) )

    def background(self, color):
        try:
            self.screen.fill( pygame.Color(color) )
        except:
            self.screen.fill( pygame.Color("white"))
        finally:
            self.bgColor = color

    def reset(self):
        self.background(self.bgColor)


       
    def setCaption(self, title):
        pygame.display.set_caption(title)

    def test(self):
        # Fill the screen with red (255, 0, 0)
        self.screen.fill(pygame.Color("red"))
        # Update the display
        self.update()

    def getSize(self):
        return self.screen.get_size()

    def getRealSize(self):
        return self.realSize

            
    







