from pathlib import Path
import shutil


class ScreenshotManager:
	def __init__(
		self,

		# Where PICO-8 saves screenshots
		source: Path,

		# How PICO-8 names screenshots.
		# Example: "celeste_*.png"
		pattern: str,

		# Where we want to move screenshots.
		target: Path
	):
		self.source = source
		self.pattern = pattern
		self.target = target
		self.target.mkdir(
			parents = True,
			exist_ok = True
		)



	def clean(self):
		shots = self.source.glob(self.pattern)
		for s in shots:
			s.unlink()
		return self



	def move(self, number: int | None = None, overwrite = False):
		shots = self.source.glob(self.pattern)

		if number == None:

			# Auto-select new directory number.
			# Chooses next highest int directory name
			number = 0
			for f in self.target.iterdir():
				try:
					number = max(
						int(f.name),
						number
					)
				except ValueError:
					continue
			number += 1

			target = self.target / str(number)
		else:
			target = self.target / str(number)

			if target.exists():
				if not overwrite:
					raise Exception(f"Target \"{target}\" exists!")
				else:
					print(f"Target \"{target}\" exists, removing.")
					shutil.rmtree(target)

		target.mkdir(parents = True)

		for s in shots:
			s.rename(target / s.name)
		return self