-- needs lua5.1-socket

function savepos()
	local name = mp.get_property("filename")
	local path = mp.get_property("path")
	local fn = mp.get_property("stream-open-filename")
	local tpos = mp.get_property("time-pos")
	print(name)
	print(tpos)
	print(path)
	print(fn)
	local host, port = "127.0.0.1", 6789
	local socket = require("socket")
	local tcp = assert(socket.tcp())
	local c = tcp:connect(host, port)
	if not c then
		mp.osd_message("syncpos: Couldn't connect")
		return
	end
	local data = "save \"" .. name .. "\" " .. tpos .. "\n"
	print("sending: " .. data)
	tcp:send(data)
	tcp:close()
	mp.osd_message("Saved position " .. tpos .. " to " .. name)
end

function getpos()
	local name = mp.get_property("filename")
	local tpos = mp.get_property("time-pos")
	print(name)
	print(tpos)
	local host, port = "127.0.0.1", 6789
	local socket = require("socket")
	local tcp = assert(socket.tcp())
	local c = tcp:connect(host, port)
	if not c then
		mp.osd_message("syncpos: Couldn't connect")
		return
	end
	local data = "get \"" .. name .. "\"\n"
	print("sending: " .. data)
	local newpos = ""
	tcp:send(data)
	local newpos = tcp:receive("*l")
	tcp:close()
	print(newpos)
	--print(s)
	--print(status)
	--print(partial)
	mp.set_property("time-pos", newpos)
	mp.osd_message("Got position " .. newpos .. " from " .. name)
end

function list()
	local host, port = "127.0.0.1", 6789
	local socket = require("socket")
	local tcp = assert(socket.tcp())
	tcp:settimeout(1)
	local c = tcp:connect(host, port)
	if not c then
		mp.osd_message("syncpos: Couldn't connect")
		return
	end
	local data = "list\n"
	print("sending: " .. data)
	tcp:send(data)
	local li = tcp:receive("*l")
	local msg = ""
	local sep = ""
	print(li)
	while (li ~= nil and li ~= "") do
		print(li)
		msg = msg .. sep .. li
		li = tcp:receive("*l")
		sep = "\n"
	end
	tcp:close()
	print(msg)
	mp.osd_message(msg)
end

mp.add_key_binding("X", "savepos", savepos)
mp.add_key_binding("C", "getpos", getpos)
mp.add_key_binding("y", "list", list)
