import sys

CSILetters = list(
	'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
)

ANSIElements = list(
	'01234567890?'
)

def lcd_cursor_up(lines=1):
	for i in range(lines):
		cur_line, cur_col = lcd1.get_cursor_pos()

		cur_line -= 1
		if cur_line < 1:
			cur_line = 4

		lcd1.set_cursor_pos(cur_line, cur_col)
	return cur_line, cur_col

def lcd_cursor_down(lines=1, reset_col=False):
	for i in range(lines):
		cur_line, cur_col = lcd1.get_cursor_pos()
		if cur_line == 4:
			lines = []
			for i in range(4):
				lcd1.set_cursor_pos(i+1,1)
				lines.append(lcd1.read_section(20))
			del lines[0]
			for i, line in enumerate(lines):
				lcd1.set_cursor_pos(i+1,1)
				lcd1.print(line)
			lcd1.set_cursor_pos(4,1)
			erase_line()
			if reset_col:
				cur_col = 1
			lcd1.set_cursor_pos(cur_line, cur_col)
		else:
			cur_line += 1
			if reset_col:
				cur_col = 1
			lcd1.set_cursor_pos(cur_line, cur_col)
	return cur_line, cur_col

def lcd_cursor_left(cols=1):
	for i in range(cols):
		cur_line, cur_col = lcd1.get_cursor_pos()

		if cur_col > 1:
			cur_col -= 1

		lcd1.set_cursor_pos(cur_line, cur_col)
	return cur_line, cur_col

def lcd_cursor_right(cols=1):
	for i in range(cols):
		cur_line, cur_col = lcd1.get_cursor_pos()

		if cur_col < 20:
			cur_col += 1
		else:
			cur_line, _ = lcd_cursor_down()
			cur_col = 1

		lcd1.set_cursor_pos(cur_line, cur_col)
	return cur_line, cur_col

def lcd_cursor_return():
	cur_line, cur_col = lcd1.get_cursor_pos()
	cur_col = 1
	lcd1.set_cursor_pos(cur_line, cur_col)

#ERASE
def erase_line():
	cur_line, cur_col = lcd1.get_cursor_pos()
	lcd1.set_cursor_pos(cur_line,1)
	for i in range(20):
		lcd1.print(' ',echo=False)
	lcd1.set_cursor_pos(cur_line, cur_col)

def erase_to_end():
	cur_line, cur_col = lcd1.get_cursor_pos()
	for i in range(cur_col,20):
		lcd1.print(' ',echo=False)
	lcd1.set_cursor_pos(cur_line, cur_col)

def ansi(string, esc_type='CSI'):
	elements = []
	element = ''
	for char in string:
		if char == ';':
			for subchar in element:
				if not subchar in ANSIElements:
					break
			else:
				try:
					elements.append(int(element))
				except ValueError:
					if element != '':
						elements.append(element)
			element = ''
			continue
		if char in CSILetters:
			op = char
			for subchar in element:
				if not subchar in ANSIElements:
					break
			else:
				try:
					elements.append(int(element))
				except ValueError:
					if element != '':
						elements.append(element)
			element = ''
			continue
		element += char
	if esc_type == 'CSI':
		if op == 'A':
			if len(elements) >= 1:
				lcd_cursor_up(elements[0])
			else:
				lcd_cursor_up()
		elif op == 'B':
			if len(elements) >= 1:
				lcd_cursor_down(elements[0])
			else:
				lcd_cursor_down()
		elif op == 'C':
			print(elements)
			if len(elements) >= 1:
				lcd_cursor_right(elements[0])
			else:
				lcd_cursor_right()
		elif op == 'D':
			print(elements)
			if len(elements) >= 1:
				lcd_cursor_left(elements[0])
			else:
				lcd_cursor_left()
		elif op == 'H':
			if len(elements) >= 2:
				lcd1.set_cursor_pos(elements[0], elements[1])
			else:
				lcd1.set_cursor_pos(1,1)
		elif op == 'J':
			if len(elements) >= 1:
				if elements[0] == 2:
					clear_save_pos = lcd1.read_address()
					lcd1.clear()
					lcd1.set_address(clear_save_pos)
				elif elements[0] == 3:
					clear_save_pos = lcd1.read_address()
					lcd1.clear()
					lcd1.set_address(clear_save_pos)
		elif op == 'K':
			if len(elements) == 0:
				elements = [0]
			if elements[0] == 0:
				erase_to_end()
			elif elements[0] == 2:
				erase_line()
		elif op == 'h':
			if len(elements) >= 1:
				if elements[0] == '?25':
					lcd1.display(1,1,1)
		elif op == 'l':
			print(elements)
			if len(elements) >= 1:
				if elements[0] == '?25':
					lcd1.display(1,0,0)

def main():
	lcd1.display(1,1,1)
	state = 'print'
	line = 0
	col = 0
	cursor_save = [0,0,0,0,0,0,0]
	while True:
		ch = ord(sys.stdin.read(1))
		print(f'{chr(ch)} | {ch}')
		if ch == 3 or ch == 4:
			break
		#ESCAPE
		if ch == 2:pass
		elif ch == 8:
			lcd_cursor_left()
		elif ch == 10:
			lcd_cursor_down(reset_col=True)
			lcd_cursor_return()
		elif ch == 13:
			lcd_cursor_return()
		elif ch == 27:
			state = 'escape'
		elif ch == 127:
			lcd_cursor_left()
		elif state == 'escape':
			if chr(ch) == '[':
				state = 'CSI'
				ansibuff = ''
			elif chr(ch) == ']':
				state = 'OSC'
				ansibuff = ''
			elif chr(ch) == 'c':
				lcd1.clear()
				lcd1.display(1,1,1)
				state = 'print'
			elif chr(ch) == '7':
				cursor_save = lcd1.read_address()
				state = 'print'
			elif chr(ch) == '8':
				lcd1.set_address(cursor_save)
				state = 'print'
			else:
				state = 'print'
		elif state == 'CSI':
			ansibuff += chr(ch)
			if chr(ch) in CSILetters:
				ansi(ansibuff, esc_type='CSI')
				state = 'print'
		elif state == 'OSC':
			ansibuff += chr(ch)
			if chr(ch) in CSILetters:
				ansi(ansibuff, esc_type='OSC')
				state = 'print'
		#PRINT
		elif state == 'print':
			cur_pos = int(''.join([str(bit) for bit in lcd1.read_address()]),2)
			if cur_pos >= 40:
				cur_pos -= 24
			cur_col = cur_pos % 20
			lcd1.print(chr(ch), echo=False)
			if cur_col == 19:
				for i in range(20):
					lcd1.shift_cursor(0)
				lcd_cursor_down(1)

	lcd1.clear()
	lcd1.display(0,0,0)
if __name__ == '__main__':
	main()
