import os
import subprocess
import pprint

def ksdiff(*strings, label="PDB"):
	if len(strings) == 0:
		print("ksdiff - pipe values to Kaleidoscope for inspection and diffing")
		print("         uses pprint.pformat() for non-string values")
		print("Usage:")
		print("	ksdiff <value>")
		print("")
		print("Examples:")
		print("	ksdiff myContentA")
		print("	ksdiff myContentB")
		print("	ksdiff myContentA, myContentB")
		print("	ksdiff myContentA, myContentB, label=\"GroupA\"")
		return

	read_paths = list()
	read_fds = list()
	write_tuples = list()

	# ensure stringyness
	strings = list(map(lambda x: x if isinstance(x, str) else pprint.pformat(x), strings))

	for string in strings:
		read_fd, write_fd = os.pipe()
		read_fds.append(read_fd)
		write_tuples.append((write_fd, string))
		path = "/dev/fd/" + str(read_fd)
		read_paths.append(path)
		
	ksdiff = subprocess.Popen(["/usr/local/bin/ksdiff", "--label", label, *read_paths], pass_fds=read_fds, close_fds=True)
	
	for (write_fd, string) in write_tuples:
		os.write(write_fd, str.encode(string, 'utf-8'))
		os.close(write_fd)

	stdout, stderr = ksdiff.communicate()
	if ksdiff.returncode != 0:
		print(stderr)
	
