# -*- coding: utf-8 -*-
"""
Écran de sélection de l'instrument

$Id$
$URL$
"""
import pygame
from eventutils import event_handler, EventDispatcher, EventHandlerMixin
from cursors import WarpingCursor
from config import FRAMERATE
from globals import BACKGROUND_LAYER
from globals import CURSOR_LAYER
from globals import hls_to_rgba_8bits


class InstrumentSelector(pygame.sprite.LayeredDirty, EventHandlerMixin) :
    
    rows = 3
    cols = 3

    def __init__(self) :
        super(InstrumentSelector, self).__init__()
        self._initCursor()
        self._initRects()
        self._initTiles()
    
    def _initRects(self) :
        screen = pygame.display.get_surface()
        tileWidth = int(round(float(screen.get_width()) / self.cols))
        tileHeight = int(round(float(screen.get_height()) / self.rows))
        
        rects = []
        for y in range(self.cols) :
            for x in range(self.rows) :
                upperLeftCorner = (y * tileWidth, x * tileHeight)
                rect = pygame.Rect(upperLeftCorner, (tileWidth, tileHeight))
                rects.append(rect)
        self.rects = rects
    
    def _initTiles(self) :
        for rect in self.rects :
            tile = InstrumentTile(self, rect)
            self.add(tile, layer=BACKGROUND_LAYER)
            
        

    def _initCursor(self) :
        self.cursor = WarpingCursor(blinkMode=True)
        self.add(self.cursor, layer=CURSOR_LAYER)


    def run(self):
        self._running = True
        clock = pygame.time.Clock()
        pygame.display.flip()
        pygame.mouse.set_visible(False)
        while self._running :
            EventDispatcher.dispatchEvents()
            dirty = self.draw(pygame.display.get_surface())
            pygame.display.update(dirty)
            clock.tick(FRAMERATE)
    
    def stop(self) :
        self._running = False
        pygame.mouse.set_visible(True)
        self.cursor._stopBlink()

    @event_handler(pygame.KEYDOWN)       
    def handleKeyDown(self, event) :
        if event.key == pygame.K_q:
            self.stop()


class InstrumentTile(pygame.sprite.DirtySprite) :

    def __init__(self, group, rect) :
        pygame.sprite.DirtySprite.__init__(self, group)
        self.rect = rect
        self.image = pygame.Surface(rect.size)
        self.image.fill((0,255,255,64))
