import kivy
import serial
import time
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.uix.image import Image

class Matrix(GridLayout):
	def __init__(self, rows, cols):
		super(Matrix,self).__init__()
		color1=204/255
		self.rows = rows
		self.cols = cols
		self.size_hint = 0.5,0.8
		self.pos_hint = {'center_x':0.3, 'center_y':0.5}
		self.Buttons = []
		self.colors = {
			10:(0.84,0.0,0.45,1.0),
			20:(0.1,0.63,0.88,1.0),
			30:(0.89,0.78,0.0,1.0),
                        40:(0.36,0.66,0.9,1.0),
                        50:(0.98,0.40,0.3,1.0),
                        60:(0.66,0.0,1.0,1.0),
			0:(0.83,0.83,0.83,0.5)
			}
		for x in range(0,self.rows*self.cols):
			self.Buttons.append(Button(text=str(x)))
			self.Buttons[x].name = x
			self.Buttons[x].background_color = self.colors.get(0)
			self.Buttons[x].led_color = 0
			self.Buttons[x].bind(on_release = self.changeColor)
			self.add_widget(self.Buttons[x])
		

	def changeColor(self, instance):
		instance.led_color += 10
		if instance.led_color == 70:
			instance.led_color = 0
		instance.background_color = self.colors.get(instance.led_color)

	def ret(self):
		print('Reset matrix')
		for x in range(0,self.rows*self.cols):
			self.Buttons[x].background_color = self.colors.get(0)
			self.Buttons[x].led_color = 0
			

class MainWindow(FloatLayout):
	def __init__(self, matrixRows, matrixCols):
		b=Button(size_hint=[0.15,0.1],pos_hint={'center_x':0.77, 'center_y':0.5},
							   background_normal= "./send2.png",border= (2, 2, 2, 2))
		b.bind(on_press = self.sendData)
		b2=Button(size_hint=[0.15,0.1],pos_hint={'center_x':0.77, 'center_y':0.35},
							   background_normal="./reset2.png",border= (5, 0, 5, 0))
		b2.bind(on_press = self.resetMatrix)
		c=Image(source='inicio.png',pos_hint={'center_x':0.77, 'center_y':0.8})
		
		super(MainWindow,self).__init__()
		self.matrixRows = matrixRows
		self.matrixCols = matrixCols
		self.size_hint=1,1
		self.pos_hint={'center_x':0.5, 'center_y':0.5}
		self.background_color = (1.0,1.0,1.0)
		self.matrix = Matrix(self.matrixRows, self.matrixCols)
		self.add_widget(self.matrix)
		self.add_widget(b)
		self.add_widget(b2)
		self.add_widget(c)
		#self.arduino = serial.Serial('COM6', 9600)

	def sendData(self, instance):
		for x in range(0,self.matrixRows*self.matrixCols):
			pin = self.matrix.Buttons[x]
			if pin.led_color != 0:
				numPin = int(pin.name)
				col = numPin/8
				fil = numPin%8
				print('M' + str(fil)+ str(col)+
				      'L' + str(pin.led_color))
				self.arduino.write('M' + str(fil)+ str(col)+ 
				      'L' + str(pin.led_color)+";")
				time.sleep(0.05)

	def resetMatrix(self,instance):
		self.matrix.ret()

		
class MainApp(App):
	title = 'StackLayout'
	def build(self):
		return MainWindow(8,8)
		
if __name__ == '__main__':
	MainApp().run()
