extends Control

signal finished

var os: String
var executable: String

var video_url: String setget set_url
var analyzed: bool = false setget set_analyzed
var audio_only: bool = false
var format_checked: bool = false setget set_format_checked
var ratelimit_checked: bool = false setget set_ratelimit_checked
var finished: bool = false
var lastLine: String = ""

onready var analyzeWarning = $Panel/Margin/Main/Settings/General/VBox/Format/Option as HBoxContainer
onready var analyzeButton = $Panel/Margin/Main/Settings/General/VBox/Format/Option/Button as Button
onready var formatCheckbox = $Panel/Margin/Main/Settings/General/VBox/Format/Checkbox as CheckBox
onready var formatMenu = $Panel/Margin/Main/Settings/General/VBox/Format/MenuButton as OptionButton
onready var rateLimitValue = $Panel/Margin/Main/Settings/Network/VBox/RateLimit/Value as LineEdit
onready var progressText = $ProgressBG/ProgressPanel/TextEdit as TextEdit
onready var downloadButton = $Panel/Margin/Main/Actions/Download as Button

func _analyze():
	run_youtubedl(["-F", video_url])

func _download():
	var output = run_youtubedl_blocking(["--get-filename", video_url])
	$FileDialog.current_file = output[0].strip_edges()
	$FileDialog.popup_centered_ratio()

func _download_with_name(name):
	run_youtubedl(["-o", name, video_url])

func set_url(new_val):
	video_url = new_val
	set_analyzed(false)
	downloadButton.disabled = video_url.length() == 0

func _url_changed(new_text):
	set_url(new_text)

func set_analyzed(new_val):
	analyzed = new_val
	analyzeWarning.visible = !analyzed
	analyzeButton.disabled = video_url.length() == 0
	formatCheckbox.disabled = !analyzed
	formatMenu.disabled = !analyzed or !format_checked

func _format_checkbox_changed(button_pressed):
	set_format_checked(button_pressed)

func set_format_checked(new_val):
	format_checked = new_val
	formatMenu.disabled = !analyzed or !format_checked

func _audio_checkbox_changed(button_pressed):
	audio_only = button_pressed

func _ratelimit_checkbox_changed(button_pressed):
	set_ratelimit_checked(button_pressed)

func set_ratelimit_checked(new_val):
	ratelimit_checked = new_val
	rateLimitValue.editable = ratelimit_checked

func _ready():
	os = OS.get_name()
	match os:
		"Windows", "UWP", "OSX", "Server", "X11":
			pass
		_:
			OS.alert("OS not supported")
			get_tree().quit(1)

var output = []
func run_youtubedl_thread(params: Array):
	output = []
	var exit = 0
	match os:
		"Windows", "UWP":
			params.push_front("bin\\youtube-dl.exe")
			exit = OS.execute("bin\\sorun_win.exe", params, true, output, true)
	finished = true

var socketUDP = null

func run_youtubedl_blocking(params):
	output = []
	var exit = 0
	match os:
		"Windows", "UWP":
			exit = OS.execute("bin\\youtube-dl.exe", params, true, output, true)
	return output
	
func run_youtubedl(params):
	print(params)
	finished = false
	var execute_thread = Thread.new()
	execute_thread.start(self, "run_youtubedl_thread", params)
	$ProgressBG.visible = true

	yield(get_tree().create_timer(0.5), "timeout")
	# Start UDP client
	socketUDP = PacketPeerUDP.new()
	socketUDP.set_dest_address("127.0.0.1", 8987)
	socketUDP.put_var(0)
	progressText.text = ""
	$Timer.start()

func _timer_tick():
	while socketUDP.get_available_packet_count() > 0:
		var newstr = socketUDP.get_packet().get_string_from_ascii() as String
		if newstr == "<EOF>\n":
			emit_signal("finished")
			return
		if newstr.ends_with("\n") == false:
			newstr += "\n"
		progressText.text += newstr
		lastLine = newstr.strip_edges()
		progressText.scroll_vertical = 999

func _on_finish():
	$ProgressBG.visible = false

func _target_selected(path):
	_download_with_name(path.strip_edges())
