#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-

# Description: Abacum, programming language
# Copyright (C) 2007 by Rafael Treviño Menéndez
# Author: Rafael Treviño Menéndez <skasi.7@gmail.com>

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import pygame
import utils
from object import Object
pygame.font.init ()

pos = None
size = None
background = None
objects = None
final = None
selected = None

SQUARE_SIZE = 50

def createBackground ():
	global background
	background = pygame.Surface (size)
	background.fill ((200, 200, 200))
	for x in xrange (0, size[0], SQUARE_SIZE):
		pygame.draw.line (background, (100, 100, 100), (x, 0), (x, size [1]))
	for y in xrange (0, size[1], SQUARE_SIZE):
		pygame.draw.line (background, (100, 100, 100), (0, y), (size [0], y))

def init (left, top, width, height):
	global pos, size, objects, final
	pos = left, top
	size = width, height
	createBackground ()
	objects = []

# *** TEST CODE
	object = Object ('Test')
	object.addSlotIn ('Bola')
	object.addSlotIn ('Bola')
	object.compile ()
	objects.append (object)

	object = Object ('Test2', (300, 0))
	object.addProperty ('Prueba', [])
	object.compile ()
	objects.append (object)
# *** TEST CODE

	final = pygame.Surface (size)

def handleSelection (newSelection):
	global selected
	selected = newSelection

def mouse (events):
	for event in events:
		mousePos = utils.relativePos (event.pos, pos)
		if event.type == pygame.MOUSEBUTTONUP:
			if selected:
				selected.mouse (pygame.MOUSEBUTTONUP, mousePos)
			handleSelection (None)
		else:
			for object in reversed (objects):
				if event.type == pygame.MOUSEBUTTONDOWN and object.rect.collidepoint (mousePos):
					object.mouse (pygame.MOUSEBUTTONDOWN, mousePos)
					handleSelection (object)
				elif event.type == pygame.MOUSEMOTION:
					if object == selected or (not selected and object.rect.collidepoint (mousePos)):
						object.mouse (pygame.MOUSEMOTION, mousePos)
					else:
						continue
				else:
					continue
				break

def update ():
	final.blit (background, (0, 0))

	for object in objects:
		s, p = object.update ()
		final.blit (s, p)

	return final
