"""
libbitmap.py
created by Jan Tóth
(C) 2017


Python module for simple work with bitmaps.

"""


"""
Container for colours.

To access defined colors, type Colours.<desired_colour>.
"""
class Colours:
	
	# 'register' as dictionary of colors?? ... register = {}
	
	#hashMap = {}
	
	WHITE = [0xff, 0xff, 0xff]
	YELLOW = [0xff, 0xff, 0x00]
	ORANGE = [0xff, 0xa5, 0x00]
	RED = [0xff, 0x00, 0x00]
	PURPLE = [0x80, 0x00, 0x80]
	BLUE = [0x00, 0x00, 0xff]
	GREEN = [0x00, 0xff, 0x00]
	GREY = [0x80, 0x80, 0x80]
	BLACK = [0x00, 0x00, 0x00]

	@classmethod
	def get_colour_from_hex(cls, hx):
		r = (hx & 0xff0000) >> 16
		g = (hx & 0x00ff00) >> 8
		b = hx & 0x0000ff
		#cls.hashMap["a"] = [10, 12]
		return [r, g, b]
		
"""
Saves given image as .PPM file.

Private function.
"""	
def _save_image_ppm(image, filename, width, height):
	ppm_header = "P6\n%d %d\n255\n" % (width, height)
	with open (filename, "w") as file:
		file.write(ppm_header)
		
	with open (filename, "ab") as file:
		for color in image:
			encoded = color.to_bytes(1, 'little')
			file.write(encoded)
		
"""
Saves given image to a file.


image		List of RGB information for each pixel in the image. <len(image) == width * height> should give True.
filename	Name that is given to the new file. If not specified, 'image' is used.
width		Image width in pixels. If not specified, 600px is used.
height		Image height in pixels. If not specified, 400px is used.
"""	
def save_image(image, filename = "image", width = 600, height = 400):
	_save_image_ppm(image, filename + ".ppm", width, height)
	
		

if __name__ == "__main__":
	image = [1, 2, 3]
	image.extend([4, 5, 6])
	print(image)
	
	print(Colours.WHITE)
	print(Colours.RED)
	print(Colours.BLUE)
	print(Colours.GREEN)
	print(Colours.BLACK)
	
	col = Colours.get_colour_from_hex(0xfaf0d5)
	print(col)
	#print(Colours.hashMap["a"])
	
	w, h = 600, 400
	image = []
	for y in range(h):
		for x in range(w):
			if 3*(400-y) > 2*x and 3*(400-y) < 1200-2*x:
				image.extend(Colours.BLUE)
			elif (400 - y) > 200:
				image.extend(Colours.WHITE)
			else:
				image.extend(Colours.RED)
				
	image_name = "flag_cz_3"
	save_image(image, image_name)
	print("Saved image as " + image_name)
