#!/usr/bin/env python3
# Very Simple Slide Show
# autor: Prymula (PRP)
# licencja: Public Domain
# data 02-09-2023
# edytor: Geany

import os, sys
import tempfile
import shutil
from sys import platform
from PIL import Image
from itertools import filterfalse

VER = "0.230913-0"

if platform == "linux" or platform == "linux2":
	SLA = '/'
elif platform == "darwin":
	SLA = '/'
elif platform == "win32":
	SLA = '\\'
	
#count = 0
tmp_path =  tempfile.mkdtemp()
#mp_path =  dir_path = os.getcwd()
#list_path =  dir_path = os.getcwd()
tmp_list = tmp_path + SLA + "list.txt"
# NIE USUWAC !
#command = "ffmpeg -framerate 0.3 -pattern_type glob -i '"+tmp_path+"/*.jpg' -c:v libopenh264 -profile:v high -crf 20 -pix_fmt yuv420p output.mp4"
command = "ffmpeg -f concat -r 0.2 -safe 0 -i '"+tmp_list+"' -framerate 1 -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p -filter:a 'atempo=0.5' output.mp4"
#command = "ffmpeg -f concat -y -r 0.2 -safe 0 -i '"+tmp_list+"' -framerate 1 -c:v mpeg4 -crf 20 -pix_fmt yuv420p output.mp4"

#num = 0
sample = None
try:
	sample = Image.Resampling.LANCZOS
	print ("Uzywam LANCZOS")
except AttributeError:
	sample = Image.ANTIALIAS
	print ("Uzywam: ANTIALIAS")
	

class App():
	
	BASE_APSC = 724
	LONG = 1080
	HALF = 540
	BASE_MICRO = 810
	BASE = None
	#n_pictures = 0
	count = 0
	
	def list_files(self, dir_path):
		res = []
		try:
			for file_path in os.listdir(dir_path):
				if os.path.isfile(os.path.join(dir_path, file_path)):
					res.append(os.path.join(dir_path, file_path))
		except FileNotFoundError:
			print(f"The directory {dir_path} does not exist")
		except PermissionError:
			print(f"Permission denied to access the directory {dir_path}")
		except OSError as e:
			print(f"An OS error occurred: {e}")
		return res

	def file_exclusion(self, files):
		for f in files[:]:
			if f.rfind('.jpg') == -1:
				#print('usuwam: '+f)
				files.remove(f)
		return files

	def get_files(self):
		dir_path = os.getcwd()  
		print ("GETCWD: "+dir_path)
		files = self.list_files(dir_path)
		return a.file_exclusion(files)

	def create_horizontal_surface(self):
		return Image.new('RGB', (a.LONG, a.BASE))
	
	def create_vertical_surface(self):
		return Image.new('RGB', (a.BASE, a.LONG))

	def put_horizontal_image(self, image):
		global sample
		new = Image.new("RGB", (a.LONG, a.BASE))
		if image.size[0] != a.LONG:
			image = image.resize((a.LONG, a.BASE), sample, None, 3.0)
		new.paste(image, (0,0), mask = image)
		return new

	def put_vertical_image(self, image):
		global sample
		new = Image.new("RGB", (a.BASE, a.LONG))
		if image.size[0] != a.BASE:
			image = image.resize((a.BASE, a.LONG), sample, None, 3.0)
		new.paste(image, (0,0), mask = image)
		return new

	# dodaje portrety do kraiobrazu
	def join_image_to_horizontal(self, image, destinity):
		global sample  # n_pictures
		single = False
		print ("DLUGOSC: "+str(len(image)))
		if len(image) == 1: #  and n_pictures > 0: # 1
			print ("SINGIELEK")
			#num += 1 # tymczasowy
			tmp = image[-1]. resize((a.HALF, a.BASE), sample, None, 3.0)
			destinity.paste(tmp, (300,0), mask = tmp)
			image.pop()
			single = True
		elif len(image) > 0:
			#num += 1 # tymczasowy
			tmp = image[-1].resize((a.HALF, a.BASE), sample, None, 3.0)
			destinity.paste(tmp, (0,0), mask = tmp)
			image.pop()
			if len(image) > 0:
				#num += 1 # tymczasowy
				tmp = image[-1]. resize((a.HALF, a.BASE), sample, None, 3.0)
				destinity.paste(tmp, (a.HALF,0), mask = tmp)
				image.pop()

		return destinity, len(image), single

	# dodaje kraiobrazy do portretu
	def join_image_to_vertical(self, image, destinity):
		global sample  # n_pictures
		single = False
		print ("DLUGOSC: "+str(len(image)))
		if len(image) ==  1: # and a.n_pictures > 0: # 1
			print ("SINGIELEK")
			#num += 1 # tymczasowy
			tmp = image[-1]. resize((a.BASE, a.HALF), sample, None, 3.0)
			destinity.paste(tmp, (0,300), mask = tmp)
			image.pop()
			single = True
			#a.n_pictures -= 1
		elif len(image) > 0:
			#num += 1 # tymczasowy
			tmp = image[-1].resize((a.BASE, a.HALF), sample, None, 3.0)
			destinity.paste(tmp, (0,0), mask = tmp)
			image.pop()
			#a.n_pictures -= 1
			if len(image) > 0:
				#num += 1 # tymczasowy
				tmp = image[-1]. resize((a.BASE, a.HALF), sample, None, 3.0)
				destinity.paste(tmp, (0, a.HALF), mask = tmp)
				image.pop()
				#a.n_pictures -= 1

		return destinity, len(image), single
		
	def read_images_from_directory(self, files):
		#global n_pictures
		images_vertical = []
		images_horizontal = []
		if len(files) == 0:
			print ('Brak plików JPG !')
			a.cleanup()
			exit (1)
		for f in files:
			image = Image.open(f).convert('RGBA')
			if image.size[1] > image.size[0]:
				s = float(image.size[0] / image.size[1]) 
				if s > 0.6 and s < 0.69:
					a.BASE = a.BASE_APSC
					print ("obraz vertical APSC: "+f+"  s:"+str(s))
					images_vertical.insert(-1, image)
					#a.n_pictures += 1
				elif s > 0.7 and s < 0.79:
					a.BASE = a.BASE_MICRO
					print ("obraz vertical MICRO: "+f+"  s:"+str(s))
					images_vertical.insert(-1, image)
					#a.n_pictures += 1 
				else:
					print ("Ver - Niedozwolony rozmiar zdjęcia s: "+str(s) + " Foto: "+f)

			if image.size[0] > image.size[1]:
				s = float(image.size[0] / image.size[1]) 
				if s > 1.4 and s <= 1.51:
					a.BASE = a.BASE_APSC
					print ("obraz horizontal APSC: "+f+"  s:"+str(s));
					images_horizontal.insert(-1, image)
					#a.n_pictures += 1
				elif s > 1.3 and s < 1.39:
					a.BASE = a.BASE_MICRO
					print ("obraz horizontal MICRO: "+f+"  s:"+str(s));
					images_horizontal.insert(-1, image)
					#a.n_pictures += 1
				else:
					print ("Hor - Niedozwolony rozmiar zdjęcia s: "+str(s) + " Foto: "+f)
				
				

		#print ("N_PICTURES: "+str(a.n_pictures))
		return images_vertical, images_horizontal
		
	def cleanup(self):
		# NIEBEZPIECZNA ! lepiej niczym innym nie nadpisywać tych zmiennych
		shutil.rmtree(tmp_path)

	def save_vertical_to_horizontal(self, images_vertical, jpg_names):
		#global count
		for i in images_vertical[:]:
			output, list_size, single = a.join_image_to_horizontal(images_vertical, a.create_horizontal_surface())
			if list_size != 0 or single == True:
				#output.show()  
				output.save(str(tmp_path)+SLA+jpg_names[a.count], format='JPEG')
				a.count += 1

	def save_horizontal_to_vertical(self, images_horizontal, jpg_names):
		#global count
		for i in images_horizontal[:]:
			output, list_size, single  = a.join_image_to_vertical(images_horizontal, a.create_vertical_surface())
			if list_size != 0 or single == True:
				#output.show()
				output.save(str(tmp_path)+SLA+jpg_names[a.count], format='JPEG')
				a.count += 1

	def save_vertical(self, images_vertica, jpg_names):
		#global count
		for i in images_vertical[:]:
			output = a.put_vertical_image(i)
			output.save(str(tmp_path)+SLA+jpg_names[a.count], format='JPEG')
			#output.show()
			images_vertical.pop()
			a.count += 1

	def save_horizontal(self, images_horizontal, jpg_names):
		#global count
		for i in images_horizontal[:]:
			output = a.put_horizontal_image(i)
			output.save(str(tmp_path)+SLA+jpg_names[a.count], format='JPEG')
			#output.show()
			images_horizontal.pop()
			a.count += 1

	def name_jpg_wihout_path(self):
		files_jpg_names = a.file_exclusion(os.listdir())
		for f in files_jpg_names:
			f = f[0] + "file "
		#print ("Ekstrat: " + str(files_jpg_names))
		return files_jpg_names

	def at_unslash(self, path):
		p = path.replace("\\","/")
		print("PO KONWERSJI: "+p)
		return p
		
	def dump_jpg_list(self, files_jpg_names):
		print("tmp_list")
		with open(tmp_list, 'w') as fp:
			for item in files_jpg_names:
				# FIXME - to nic nie daje dalej wyrzuca "invalid argument"
				if platform == "win32":
					fp.write("file '"+a.at_unslash(str(tmp_path) + SLA +"%s'\r\n" % item))
				else:
					# write each item on a new line
					fp.write("file '"+str(tmp_path) + SLA +"%s'\r\n" % item)
				
				print("Zapisany plik do list.txt --> "+item)
		return files_jpg_names
a = App()
jpg_names = a.dump_jpg_list(a.name_jpg_wihout_path())
if len(sys.argv) == 1 or sys.argv[-1] == '-H':
	images_vertical, images_horizontal = a.read_images_from_directory(a.get_files())
	a.save_horizontal(images_horizontal, jpg_names)
	a.save_vertical_to_horizontal(images_vertical, jpg_names)
	#print ("_---------------N_PIC: "+str(a.n_pictures))

	print(command)
	os.popen(command).read()
elif sys.argv[-1] == '-V':
	images_vertical, images_horizontal = a.read_images_from_directory(a.get_files())
	a.save_vertical(images_vertical, jpg_names)
	a.save_horizontal_to_vertical(images_horizontal, jpg_names)
	#print ("_---------------N_PIC: "+str(a.n_pictures))
	print(command)
	os.popen(command).read()
else:
	print ("\n\nUżycie:\n\n Uruchom skrypt w katalogu z plikami JPG\n\n   'vsss -H' | 'vsss'  dla video horyzontalnego\n   'vsss -V'   dla video vertykalnego\n\n \
	'vsss -h'  aby wyświetlić pomoc i numer wersji.\n		verysimpleslideshow (vsss) ver. "+VER+"\n                SEPT-2023")


a.cleanup()
