import sys
import os
import pip
import re
import shutil
import argparse
from pydub import AudioSegment
from collections import defaultdict
try:
	import soundfile as sf
except:
	pip.main(['install', 'soundfile'])
	import soundfile as sf

# Specify the path to ffmpeg or avconv executable
ffmpeg_path = "C:\ffmpeg\\"

# Set the environment variable
os.environ["PATH"] += os.pathsep + os.path.dirname(ffmpeg_path)

def convert_ogg_files(in_path, out_path, otype, rate):
	for file_name in os.listdir(in_path):
		if file_name.endswith(".ogg"):
			print(f"File {file_name}")
			ogg_file = os.path.join(in_path, file_name)
			if not "ogg" in otype:
				file_name = file_name.replace(".ogg", ".wav")
			out_file = os.path.join(out_path, file_name)
			ogg_audio = AudioSegment.from_ogg(ogg_file)
			out_audio = ogg_audio.set_channels(1).set_sample_width(2)
			if "ogg" in otype:
				out_audio.export(out_file, format="ogg", parameters=["-ar", str(rate)])
			elif "adpcm" in otype:
				if "_LOOP" in out_file:
					duration_ms = int(ogg_audio.duration_seconds * 1000)
					out_file = out_file.replace(".wav", f"_T{duration_ms}.wav")
				out_audio.export(out_file, format="wav", codec="adpcm_ima_wav", parameters=["-ar", str(rate)])
			elif "wav" in otype:
				out_audio.export(out_file, format="wav", codec="pcm_s16le", parameters=["-ar", str(rate)])

def move_txt_files(in_path, out_path):
	for file_name in os.listdir(in_path):
		if file_name.endswith(".txt"):
			print(f"File {file_name}")
			src_file = os.path.join(in_path, file_name)
			dst_file = os.path.join(out_path, file_name)
			shutil.copy(src_file, dst_file)
			

def main(argv):	
	#Parse arguments ######################################
	parser = argparse.ArgumentParser()
	parser.add_argument('path', help='Path to sound folder')
	parser.add_argument('--otype', choices=['wav', 'ogg' ,'adpcm'], default='ogg', help='Output file type')
	parser.add_argument('--rate', choices=['32000', '44100' ,'16000'], default='32000', help='Sample rate')
	args = parser.parse_args()
	
	orig_path = os.path.join(args.path, "orig")
	if not os.path.exists(orig_path):
		print("Moving original files to subfolder")
		os.makedirs(orig_path)
		for file_name in os.listdir(args.path):
			file_path = os.path.join(args.path, file_name)
			if os.path.isfile(file_path):
				shutil.move(file_path, os.path.join(orig_path, file_name))

	for file_name in os.listdir(args.path):
		file_path = os.path.join(args.path, file_name)
		if os.path.isfile(file_path):
			os.remove(file_path)
	convert_ogg_files(orig_path, args.path, args.otype, args.rate)
	move_txt_files(orig_path, args.path)

if __name__ == "__main__":
	main(sys.argv[1:])