--- modification by jguer
--- default keybinding: b
local utils = require("mp.utils")
local mp = require("mp")
local msg = require("mp.msg")

local subl = "/bin/subdl"
local lang_list = { "eng" }

local function startswith(text, prefix)
	return text:find(prefix, 1, true) == 1
end

local function load_sub_from_file()
	local path = mp.get_property("path")
	local t = {}

	if path == nil or path == "" or startswith(path, "http") then
		return t
	end

	for i, lang in ipairs(lang_list) do
		t[i] = {}
		t[i].res = mp.command_native({
			name = "subprocess",
			args = {
				subl,
				"--existing=bypass",
				string.format("--lang=%s", lang),
				string.format("--output={m}.{M}.%s.srt", lang),
				path,
			},
		})
		t[i].sub_path = path .. "." .. lang .. ".srt"
		t[i].sub_lang = lang
	end
	return t
end

local function load_sub_from_title()
	local title = mp.get_property("media-title")
	local t = {}
	if title == nil or title == "" then
		return t
	end

	msg.info(("searching:%s"):format(title))

	local wd = mp.get_property("working-directory")
	local path = wd .. "/" .. title .. ".tmp"
	local f = io.open(path, "w")

	f:write("generated by mpv auto-sub\n")
	f:close()

	for i, lang in ipairs(lang_list) do
		t[i] = {}
		t[i].res = mp.command_native({
			name = "subprocess",
			args = {
				subl,
				"--existing=bypass",
				string.format("--lang=%s", lang),
				string.format("--search=%s", title),
				string.format("--output={m}.{M}.%s.srt", lang),
				path,
			},
		})
		t[i].sub_path = path .. "." .. lang .. ".srt"
		t[i].sub_lang = lang
	end

	os.remove(path)
	return t
end

local function load_sub_fn()
	mp.osd_message("Searching subtitle")
	local res = load_sub_from_file()
	local reload = false
	local sub_paths = {}
	for _, t in ipairs(res) do
		if t.res.status == 0 then
			reload = true
			local i_sub = #sub_paths + 1
			sub_paths[i_sub] = {}
			sub_paths[i_sub].path = t.sub_path
			sub_paths[i_sub].lang = t.sub_lang
		end
	end

	if not reload then
		res = load_sub_from_title()
		for _, t in ipairs(res) do
			if t.res.status == 0 then
				reload = true
				local i_sub = #sub_paths + 1
				sub_paths[i_sub] = {}
				sub_paths[i_sub].path = t.sub_path
				sub_paths[i_sub].lang = t.sub_lang
			end
		end
	end

	if reload then
		mp.osd_message(string.format("Subtitles downloaded: %d", #sub_paths))
		for _, sub_path in ipairs(sub_paths) do
			mp.command_native_async({ name = "sub-add", url = sub_path.path, lang = sub_path.lang })
		end
	else
		mp.osd_message("Did not find subtitle")
	end
end

mp.add_key_binding("b", "auto_load_subs", load_sub_fn)
