import sys

CSILetters = list(
	'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
)

ANSIElements = list(
	'01234567890?'
)

hit_end = False
def test_hit_end():
	global hit_end
	if hit_end:
		hit_end = False
		lcd_cursor_down(reset_col=True)

def lcd_cursor_up(lines=1):
	test_hit_end()
	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, ignore_hit_end=False, reset_col=False):
	global hit_end
	if ignore_hit_end:
		hit_end = False
	else:
		test_hit_end()
	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(lcd1)
			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):
	test_hit_end()
	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):
	test_hit_end()
	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():
	hit_end = False
	cur_line, cur_col = lcd1.get_cursor_pos()
	cur_col = 1
	lcd1.set_cursor_pos(cur_line, cur_col)

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

def erase_to_end(lcd):
	global hit_end
	if hit_end:
		return
	cur_line, cur_col = lcd.get_cursor_pos()
	for i in range(cur_col-1,20):
		lcd.print(' ',echo=False)
	lcd.set_cursor_pos(cur_line, cur_col)

def ansi(string, esc_type='CSI'):
	global hit_end, buff
	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':
			hit_end = False
			if len(elements) >= 1:
				lcd_cursor_down(elements[0])
			else:
				lcd_cursor_down()
		elif op == 'C':
			if len(elements) >= 1:
				lcd_cursor_right(elements[0])
			else:
				lcd_cursor_right()
		elif op == 'D':
			if len(elements) >= 1:
				lcd_cursor_left(elements[0])
			else:
				lcd_cursor_left()
		elif op == 'H':
			hit_end = False
			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(lcd1)
			elif elements[0] == 2:
				erase_line(lcd1)
		elif op == 'h':
			if len(elements) >= 1:
				if elements[0] == '?25':
					lcd1.display(1,1,1)
				elif elements[0] == '?1049':
					buff.set_secondary_buffer()
		elif op == 'l':
			if len(elements) >= 1:
				if elements[0] == '?25':
					lcd1.display(1,0,0)
				elif elements[0] == '?1049':
					buff.set_primary_buffer()

class Buffer:
	def __init__(self, lcd):
		self.lcd = lcd
		self.primary_buffer = lcd.read_all()
		self.primary_location = lcd.get_cursor_pos()
		self.secondary_buffer = [
			f'{"":<20}',
			f'{"":<20}',
			f'{"":<20}',
			f'{"":<20}'
		]
		self.secondary_location = (1,1)
		self.buffer = 'primary'

	def set_primary_buffer(self):
		if self.buffer == 'primary':return
		self.secondary_buffer = self.lcd.read_all()
		self.secondary_location = self.lcd.get_cursor_pos()
		for i, line in enumerate(self.primary_buffer):
			self.lcd.set_cursor_pos(i+1,1)
			self.lcd.print_line(line)
		self.lcd.set_cursor_pos(*self.primary_location)
		self.buffer = 'primary'

	def set_secondary_buffer(self):
		if self.buffer == 'secondary':return
		self.primary_buffer = self.lcd.read_all()
		self.primary_location = self.lcd.get_cursor_pos()
		for i, line in enumerate(self.secondary_buffer):
			self.lcd.set_cursor_pos(i+1,1)
			self.lcd.print_line(line)
		self.lcd.set_cursor_pos(*self.secondary_location)
		self.buffer = 'secondary'

def main():
	global hit_end, buff
	buff = Buffer(lcd1)
	lcd1.display(1,1,1)
	state = 'print'
	prev_state = ''
	line = 0
	col = 0
	cursor_save = [0,0,0,0,0,0,0]
	while True:
		ch = ord(sys.stdin.read(1))
		if ch == 3 or ch == 4:
			break
		#ESCAPE
		if state == 'ESCAPE':
			lcd2.print(chr(ch))
			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':
			lcd2.print(chr(ch))
			ansibuff += chr(ch)
			if chr(ch) in CSILetters:
				ansi(ansibuff, esc_type='CSI')
				state = 'print'
		elif state == 'OSC':
			lcd2.print(chr(ch))
			ansibuff += chr(ch)
			if chr(ch) in CSILetters:
				ansi(ansibuff, esc_type='OSC')
				state = 'print'
		#PRINT
		elif state == 'print':
			if ch == 2:pass
			elif ch == 8:
				lcd_cursor_left()
			elif ch == 10:
				lcd_cursor_down(ignore_hit_end=True, reset_col=True)
				lcd_cursor_return()
			elif ch == 13:
				lcd_cursor_return()
			elif ch == 27:
				state = 'ESCAPE'
				lcd2.set_cursor_pos(1,1)
				erase_line(lcd2)
				lcd2.print('^[')
			elif ch == 127:
				lcd_cursor_left()
			else:
				test_hit_end()
				cur_line, cur_col = lcd1.get_cursor_pos()
				lcd1.print(chr(ch), echo=False)
				print(f'\033[{cur_line};{cur_col}H', end='')
				print(chr(ch), end='')
				if cur_col == 20:
					lcd1.shift_cursor(0)
					hit_end = True
		if state in ['ESCAPE', 'CSI', 'OSC']:
			lcd2.display(1,1,0)
			lcd2_escape_cur = lcd2.get_cursor_pos()
			lcd2.set_cursor_pos(2,1)
			lcd2.print_line(f'-- {state} --')
			lcd2.set_cursor_pos(*lcd2_escape_cur)
		elif state != prev_state:
			lcd2.display(1,0,0)
			lcd2.set_cursor_pos(2,1)
			lcd2.print_line('-- NORMAL --')
#		print(f'{chr(ch)} | {ch}')
#		sleep(1)

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