import requests
import json
import time

URL = "https://api.aditu.eus/"
API_ID = "YOUR_API_ID"
API_KEY = "YOUR_API_KEY"
FILE_ID = YOUR_FILE_ID
FROM_LANG = 'eu'
TO_LANG = 'es'


def translate_file_api(api_id, api_key, from_language, to_language, file_id):
	print("Translating: %s" % file_id)
	PARAMS = {"api_id":api_id, "api_key": api_key, "from_language": from_language, "to_language": to_language, "file_id": file_id}
	r = requests.post(url = URL + "translate", data = PARAMS)
	if r.status_code != 200:
		print(r.content)
		print("There was an error: %d" % r.status_code)
		return None
	return r.json()

def get_translation_api(api_id, api_key, task_id):
	PARAMS = {"api_id":api_id, "api_key": api_key, "task_id": task_id}
	r = requests.post(url = URL + "get_translation", data = PARAMS)
	if r.status_code != 200:
		print(json.loads(r.content))
		print("There was an error: %d" % r.status_code)
	return r


def translate_file(api_id, api_key, from_language, to_language, file_id):
	response = translate_file_api(api_id, api_key, from_language, to_language, file_id)
	if not response:
		return False
	print("File succesfully sent to server")
	retries = 0
	while True:
		if retries == 5:
			return False
		time.sleep(2)
		result = get_translation_api(api_id, api_key, response["task_id"])
		result_content = json.loads(result.content)
		if result.status_code == 200:
			if result_content["finished"] and not result_content["error"]:
				print(result_content)
				open(result_file, 'wb').write(result_content["translated_subtitles"].encode('utf-8'))
				return True
			elif result_content["finished"] and result_content["error"]:
				return False
		else:
			retries += 1




result = translate_file(API_ID, API_KEY, FROM_LANG, TO_LANG, FILE_ID)
if result:
	print("File succesfully translated")
else:
	print("There was an error")
