#!/usr/bin/env python

# This file needs to be rewritten!

from os import system
import curses



def chatWindows(screen,users,emails,window,user_input):
	curses.start_color()
	background_color = curses.COLOR_BLACK
	curses.init_pair(1, curses.COLOR_GREEN, background_color)
	curses.init_pair(2, curses.COLOR_YELLOW, background_color)
	curses.init_pair(3, curses.COLOR_RED, background_color)

	screen.clear()
	screen.box()
	offset = 0
	offset2 = 0
	if window[0]:
		offset = 16
	if window[1]:
		offset2 = 32-offset

	user_size = screen.getmaxyx()
	window_size_y,window_size_x = screen.getmaxyx()

	if window_size_x>38+offset+offset2 and window_size_y>7:
		# If window is toggled
		if window[0]:
			win1 = screen.subwin(window_size_y, 17, 0, 0)
			win1.box()
			i = 1;
			longestOffset = len(str(len(users)))
			for user in users:
				if window_size_y-1>i:
					numberOffset = longestOffset-len(str(i))
					win1.addstr(i,1,"%s %s" % (numberOffset*" "+str(i),user[0:14-longestOffset]))
				i += 1
			win1.refresh()

		# If window is toggled
		if window[1]:
			win2 = screen.subwin(window_size_y,33-offset,0,window_size_x-33+offset)
			win2.box()
			i = 1
			for email in emails:
				if window_size_y-1>i:
					win2.addstr(i,1,"%s" % email[0:31-offset])
				i += 1

			win2.refresh()

		# Using offsets to create the new sub window.
		space_left = window_size_x-offset2-offset
		winMessages = screen.subwin(window_size_y,space_left,0,offset)
		i = window_size_y-2
		for data in reversed(user_input):
			if 1<i:
				# length of timestap and nick; +4 = 3 spaces and one ":"
				startMessageAt = len(data[1])+len(data[0])+4 
				# tricky part is to get message dynamic with window!
				text_space = space_left-startMessageAt-1
				text = []
				string = ""
				for word in data[2].split(" "):
					if len(word)>text_space:
						while(len(word)>text_space):
							text.append(word[0:text_space+1])
							word = word[text_space:]
					if len(string+word)>text_space:
						text.append(string)
						string = ""
					string = string+word+" "

				text.append(string)
				x = len(text)
				if 0<i-x+1:
					#timestamp
					winMessages.addstr(i-x+1,1,data[0],curses.color_pair(2))
					#name
					winMessages.addstr(i-x+1,len(data[0])+2,data[1]+":",curses.color_pair(3))
					for line in text:
						winMessages.addstr(i-x+1,startMessageAt,line[0:-1],curses.color_pair(1))
						x -= 1

				i -= len(text)
				# end of tricky part
			

	elif window_size_x>14 and window_size_y>3:
		screen.addstr(0,0,"Screen to small")
		screens = ""
		if window[0]:
			screens += " 1"
		if window[1]:
			screens += " 2"
		screen.addstr(1,0,"Enabled screens:%s" % screens)

