# -*- coding: utf-8 -*-

"""
	'io' test set : tests regarding the pygconsole.io submodule
	Test 104 : Display a long text and scroll the screen up and down.
	ESCAPE Key to exit.
"""


# Standard modules
#-----------------
import sys
import os
from collections import namedtuple
import logging

# Third party modules
#--------------------
import pygame
from pygame.locals import *
from colorlog import ColoredFormatter

# Internal modules
#-----------------
if __name__ == '__main__':
	sys.path.append(os.path.join(os.path.dirname(__file__),'..'))
	import pygconsole
else:
	from .. import pygconsole

# namedtuples
#------------
Coordinates = namedtuple("Coordinates", "x y")
Colour = namedtuple("Colour", "red green blue alpha")

# Global constants
#-----------------
RESOURCE_DIR = os.path.join(os.path.dirname(__file__),"resources") # directory where graphical resources are stored
BACKGROUND_IMAGE = os.path.join(RESOURCE_DIR,"background.jpg") # Background image
FONT = None # Font displayed outside of the console (None = default pygame font)

DISPLAY_SIZE = Coordinates(1920,1080) # screen resolution
CONSOLE_COORDINATES = Coordinates(1000,620) # upper left corner coordinates of the console
FRAMERATE = 50 # Maximum number of displaying loops per second

FONT_SIZE = 40 # size of the font displayed on the screen, but out of the console
FONT_COLOUR = Colour(255,0,0,255) # Colour of the font displayed outside of the console
TEXT_COORDINATES = Coordinates(50,50) # Coordinates of the first line of the text displayed outside of the console

TEXT_LIST = [
	"Test 101: Display a long text and scroll the screen up and down.",
	"Press the 'up' arrow key to scroll up,",
	"press the 'down' arrow key to scroll down.",
	"ESCAPE key to exit."
			]

LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur pellentesque eleifend tempus. Vivamus lobortis, quam at tristique aliquet, tortor nisl tincidunt lectus, sed tincidunt ipsum augue vitae quam. Mauris auctor dui nec eros facilisis consequat. Mauris vulputate lectus sem, eu feugiat est volutpat eu. Donec facilisis neque odio, vel ultrices orci blandit et. Proin sem lorem, mollis ac dignissim ac, convallis vitae arcu. Morbi malesuada magna sed dolor elementum pellentesque. Nunc quis ipsum a metus ultricies pulvinar. Vivamus orci dui, varius in leo a, dapibus commodo ipsum. Phasellus sapien lectus, porttitor nec augue nec, viverra faucibus arcu.\x0d\x0aQuisque cursus sollicitudin diam id sagittis. Curabitur gravida in purus at pharetra. Vestibulum id dolor nulla. Donec pharetra sed dui eget euismod. Nunc tellus turpis, interdum sed imperdiet at, eleifend sit amet tortor. Quisque vulputate felis ut mollis ullamcorper. Nam condimentum elit ex. Phasellus rutrum orci vitae urna auctor, sit amet porta urna hendrerit. In non maximus mi.\x0d\x0aNunc pharetra ligula non nisi dapibus, quis congue erat mattis. Ut fermentum pulvinar velit ut malesuada. Maecenas sodales maximus nisi id ornare. Quisque vehicula posuere neque quis feugiat. Mauris mi tortor, dictum blandit cursus ac, accumsan ut erat. Suspendisse imperdiet mi ut metus luctus ultrices. In vehicula convallis nulla, at pellentesque orci bibendum sed.\x0d\x0aMaecenas lacinia est et ultricies pharetra. Aliquam at dapibus metus. Fusce euismod lacus sodales, rhoncus odio non, ullamcorper nulla. Sed orci libero, euismod non facilisis vel, viverra nec dui. Mauris pretium fringilla tellus euismod pulvinar. Praesent id augue elit. Nam est purus, imperdiet id sodales sed, fringilla a tortor. Mauris quis bibendum libero. Praesent vestibulum consectetur sem, ut venenatis risus dapibus et. Fusce convallis felis laoreet ipsum egestas convallis. Maecenas ut faucibus ligula. Vivamus nec mollis mauris. Vivamus aliquam venenatis tellus porttitor tincidunt. Phasellus lobortis viverra tincidunt. Nam enim felis, condimentum et aliquam ac, tincidunt a mi. Nulla eget tortor nulla."

# Dataclasses
#------------

# Classes
#--------


# Functions
#----------


# Main function
#--------------
def main():
	""" Main program execution"""
	
	# Logging initialization
	formatter = ColoredFormatter(
			'%(log_color)s[%(asctime)s][%(levelname)s][%(name)s]:%(message)s',
			datefmt='%Y-%m-%d %H:%M:%S',
			reset=True,
			log_colors={
					'DEBUG':	'cyan',
					'INFO':		'green',
					'WARNING':	'yellow',
					'ERROR':	'red',
					'CRITICAL':	'red,bg_white'
			},
			secondary_log_colors={},
			style='%'
		)
	handler = logging.StreamHandler()
	handler.setLevel(logging.DEBUG)
	handler.setFormatter(formatter)
	log = logging.getLogger('display')
	log.setLevel(logging.DEBUG)
	log.addHandler(handler)
	
	
	# screen initialization
	pygame.init()
	clock = pygame.time.Clock() # timer to control framerate
	flags = FULLSCREEN|SCALED|DOUBLEBUF
	screen_surface = pygame.display.set_mode(size=DISPLAY_SIZE,flags=flags)
	background_surface = pygame.image.load(BACKGROUND_IMAGE)
	
	# Font initialization
	font = pygame.font.Font(FONT,FONT_SIZE)
	line_space = font.get_linesize()
	
	# console initialization
	console = pygconsole.console.Console.get_console(name="pygame_console",logger = log)
	iotextstream = pygconsole.io.TextIOConsoleWrapper(console_name="pygame_console", newline='\r\n', line_buffering=True)
	
	# Print long text
	print(LONG_TEXT, file=iotextstream, flush=True)
	
	# Displaying loop
	while True:
		clock.tick(FRAMERATE)
		
		# Events
		for event in pygame.event.get():
			if event.type == QUIT: sys.exit()
			if event.type == KEYDOWN:
				if event.key == K_ESCAPE:
					sys.exit()
				elif event.key == K_UP:
					print("\x1b[1S", file=iotextstream, flush=True) # Scroll up 1 line
				elif event.key == K_DOWN:
					print("\x1b[1T", file=iotextstream, flush=True) # Scroll down 1 line
		
		# Background display
		screen_surface.blit(background_surface,(0,0))
		
		# Text display
		text_line_coordinates = TEXT_COORDINATES
		for text_line in TEXT_LIST:
			text_surface = font.render(text_line,True,FONT_COLOUR)
			screen_surface.blit(text_surface,text_line_coordinates)
			text_line_coordinates = text_line_coordinates._replace(y=text_line_coordinates.y+line_space)
		
		# Console display
		screen_surface.blit(console.surface,CONSOLE_COORDINATES)
		
		# Screen rendering
		pygame.display.flip()


# Main program,
# running only if the module is NOT imported (but directly executed)
#-------------------------------------------------------------------
if __name__ == '__main__':
	main()
	