import time
import random

import virtualtimers
import rgb
import defines
import buttons
import system

random.seed(int(time.time()))

pixels = [0x000000FF] * 256
pixels2 = [0x000000FF] * 256
age = 0
c = 0

def prep():
    "Prepare initial state"
    global pixels
    for x in range(256):
        pixels[x] = 0x000000FF
    for color in [0xFF0000FF, 0x00FF00FF, 0x0000FFFF]:
        for z in range(random.randint(30,60)):
            pixels[random.randint(0,255)] |= color

def livelife():
    "Run simulation"
    global pixels
    global pixels2
    global c
    color = [0xFF0000FF, 0x00FF00FF, 0x0000FFFF][c]
    for y in range(8):
        for x in range(32):
            neighbours = 0
            for checkx, checky in [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]:
                if pixels[((x + checkx) % 32) + 32 * ((y + checky) % 8)] & color == color:
                    neighbours += 1
            if pixels[x + 32 * y] & color == color and (neighbours < 2 or neighbours > 3):
                pixels2[x + 32 * y] = pixels[x + 32 * y] - (color & 0xFFFFFF00)
            elif pixels[x + 32 * y] & color == 0xFF and neighbours == 3:
                pixels2[x + 32 * y] = pixels[x + 32 * y] | color
            else:
                pixels2[x + 32 * y] = pixels[x + 32 * y]
    for i, p in enumerate(pixels2):
        pixels[i] = p
    c = (c + 1) % 3

def update():
    global age
    if age == 0:
        prep()
        age += 1
    else:
        livelife()
        rgb.clear()
        rgb.image(pixels, (0,0), (32,8))
        age += 1
    if age > 500:
        age = 0
    return 100

def input_b(pressed):
    if pressed:
        system.reboot()

def input_a(pressed):
    global age
    if pressed:
        age = 0

buttons.register(defines.BTN_B, input_b)
buttons.register(defines.BTN_A, input_a)

prep()
rgb.image(pixels, (0,0), (32,8))

virtualtimers.begin(100)
virtualtimers.new(0, update)