function descriptor()

  return { title = "Scenerixx VLC Bridge",
    version = "0.2",
    author = "ScenerixxDev",
    url = "www.scenerixx.com",
	shortdesc = "Scenerixx VLC Bridge",
	description = "This plugin is a bridge into your local Scenerixx installation",
	capabilities = {"menu", "input-listener", "meta-listener", "playing-listener"},
  }
end

function get(url)
  vlc.msg.dbg("passed url: "..url)
  local u = vlc.net.url_parse(url)
  vlc.msg.dbg("passed options: "..u["option"])
  local host, port, path, params = u["host"], u["port"], u["path"], u["option"]
  local header = {
    "GET "..path.."?"..params.." HTTP/1.1",
    "Host: "..host,
    "",
    ""
  }
  --vlc.msg.dbg("header: "..header)
  local request = table.concat(header, "\r\n")
  vlc.msg.dbg("request: "..request)
  return http_req(host, port, request)
end

function http_req(host, port, request)
  vlc.msg.dbg("host "..host)
  vlc.msg.dbg("port "..port)
  vlc.msg.dbg("request "..request)
  local fd = vlc.net.connect_tcp(host, port)
  if not fd then return false end
  local pollfds = {}

  pollfds[fd] = vlc.net.POLLIN
  vlc.net.send(fd, request)
  vlc.net.poll(pollfds)

vlc.msg.dbg("start receivingX")
  local chunk = vlc.net.recv(fd, 2048)
  vlc.msg.dbg("chunk: "..chunk)
---  while chunk do
---    vlc.msg.dbg("chunk "..chunk)
---    chunk = vlc.net.poll(pollfds)
    --chunk = vlc.net.recv(fd, 1024)
	  --  vlc.net.poll(pollfds)
---  end
	for i = 1,10,1 
	do 
	--	vlc.net.poll(pollfds)
	end
  vlc.msg.dbg("close now ")
  vlc.net.close(fd)
  return chunk
end

function activate()
vlc.msg.dbg("activate")
  return true
end

-- Activate & Deactivate
function activate2()
-- must be activated by the user: https://forum.videolan.org/viewtopic.php?t=140576

  vlc.osd.message("Scenerixx Bridge activated")
  vlc.msg.dbg("Plugin activated. Current time "..getTimePassed())

	-- TODO: does not work yet
	if (vlc.input.item() == nil) then
		vlc.osd.message("Cannot activate - no video loaded")
		return
	else
		local item = vlc.input.item()
		local uri = item:uri()
		uri = string.gsub(uri, '^file:///', '')
		uri = string.gsub(uri, '/', '\\')
		vlc.osd.message("Current video: " .. uri)
	end  
  
		vlc.msg.dbg("duration formatted: "..getFormatedTime())
		
  
  vlc.msg.dbg("uri "..getCurrentFile())
  close()
end

function getFormatedTime()
  local duration = getTimePassed()
  duration = duration / 1000 / 1000
  vlc.msg.dbg("duration raw: "..duration)
  --globalstart = duration
  
  local formatedTime = string.format("%02d:%02d:%02d",
                         math.floor(duration/3600),
                         math.floor(duration/60)%60,
                         math.floor(duration%60))
						 	
							vlc.msg.dbg("hi: "..formatedTime)
	if (formatedTime == nil) then
		return -1
	else
		return formatedTime	
	end
end

function getCurrentFile()
		local item = vlc.input.item()
		local uri = item:uri()
		vlc.msg.dbg("current uri: "..uri)
		uri = string.gsub(uri, '&', '%%26')
		uri = string.gsub(uri, '^file:///', '')
		uri = string.gsub(uri, '\\', '\\\\')
		vlc.msg.dbg("current file "..uri)
		return uri
end

function close()
  vlc.msg.dbg("[Scenerixx Bridge] Close")
end

function deactivate()

  local duration = getTimePassed()
  duration = duration / 1000 / 1000
  vlc.msg.dbg("time passed on deactivation: "..duration)
end

function menu()
    -- related to capabilities={"menu"} in descriptor()
    -- menu occurs in VLC menu: View > Extension title > ...
    return {
	"Mark movie as favorite", 
	"Mark scene as favorite",
    "Remaining time in scene", 
	"I came", 
	"Add scene starting at current position", 
	"Set end time for scene", 
	"Add bookmark starting at current position", 
	"Set end time for bookmark",
	"Show types",
	"Show current rating",
	"Set rating",
	"Show current immersion",
	"Set immersion"
--	"Select current movie in list"
	}
end

-- Function triggered when an element from the menu is selected
function trigger_menu(id)
    if(id == 1) then
		markMovieAsFavorite()		
    elseif(id == 2) then
		markSceneAsFavorite()
    elseif(id == 3) then
		remainingTimeInScene()	
    elseif(id == 4) then
		iCame()	
    elseif(id == 5) then
		addScene()
    elseif(id == 6) then
		setSceneEndtime()
    elseif(id == 7) then
		addBookmark()
    elseif(id == 8) then
		setBookmarkEndtime()
    elseif(id == 9) then
		getMovieTypes()
    elseif(id == 10) then
		getRating()
    elseif(id == 11) then
		setRating()
    elseif(id == 12) then
		getImmersion()
    elseif(id == 13) then
		setImmersion()
    --elseif(id == 9) then
	--	selectInList()
    end
end

function markMovieAsFavorite()
    vlc.msg.dbg("mark movie as favorite: "..getCurrentFile())
    local res = get("http://localhost:7679/api/v1/markMovieAsFavorite?filename="..getCurrentFile())
    if(string.find(res, "marked as favorite")) then
        vlc.osd.message("Marked movie as favorite")
    else
	vlc.osd.message("An error occured - Could not find movie")
    end
end

function markSceneAsFavorite()
	vlc.msg.dbg("mark scene as favorite")
    local res =	get("http://localhost:7679/api/v1/markSceneAsFavorite?filename="..getCurrentFile().."&time="..getFormatedTime())
    if(string.find(res, "marked as favorite")) then
        vlc.osd.message("Marked scene as favorite")
    else
	vlc.osd.message("An error occured - Could not find scene or movie")		
    end
end


function remainingTimeInScene()
    vlc.msg.dbg("remainingTimeInScene")
    local res = get("http://localhost:7679/api/v1/remainingTimeInScene?filename="..getCurrentFile().."&time="..getFormatedTime())
    if(string.find(res, "remainingTimeInScene")) then
	vlc.osd.message("An error occured - maybe no scene length set")		
    else
	vlc.osd.message("Remaining time: "..res.sub(res, string.len(res) - 8, string.len(res)))
    end
end

function iCame()
    vlc.msg.dbg("iCame")
    local res = get("http://localhost:7679/api/v1/iCame?filename="..getCurrentFile().."&time="..getFormatedTime())
    if(string.find(res, "i came")) then
	vlc.osd.message("I came at "..getFormatedTime())
    else
	vlc.osd.message("An error occured - maybe no scene length set")		
    end
end

function addScene()
    vlc.msg.dbg("add scene: "..getFormatedTime())
    local res = get("http://localhost:7679/api/v1/addScene?filename="..getCurrentFile().."&time="..getFormatedTime())
    if(string.find(res, "Added scene ")) then
        vlc.osd.message("Added scene at "..getFormatedTime())
    else
	vlc.osd.message("An error occured - Could not find movie")
    end
end

function setSceneEndtime()
    vlc.msg.dbg("set scene endtime: "..getFormatedTime())
    local res = get("http://localhost:7679/api/v1/setSceneEndTime?filename="..getCurrentFile().."&time="..getFormatedTime())
    if(string.find(res, "Set end time on scene")) then
        vlc.osd.message("Added scene endtime at "..getFormatedTime())
    else
	vlc.osd.message("An error occured - probably no start time set yet")
    end
end

function addBookmark()
    vlc.msg.dbg("add bookmark: "..getFormatedTime())
    local res = get("http://localhost:7679/api/v1/addBookmark?filename="..getCurrentFile().."&time="..getFormatedTime())
    if(string.find(res, "Added bookmark to")) then
        vlc.osd.message("Added bookmark at "..getFormatedTime())
    else
	vlc.osd.message("An error occured - Scene or movie not found")		
    end
end

function setBookmarkEndtime()
    vlc.msg.dbg("set bookmark endtime: "..getFormatedTime())
    local res = get("http://localhost:7679/api/v1/setBookmarkEndTime?filename="..getCurrentFile().."&time="..getFormatedTime())
    if(string.find(res, "Set end time on bookmark")) then
        vlc.osd.message("Added bookmark endtime at "..getFormatedTime())
    else
	vlc.osd.message("An error occured - probably no start time set yet")		
    end
end

function getMovieTypes()
    vlc.msg.dbg("getMovieTypes: "..getFormatedTime())
    local res = get("http://localhost:7679/api/v1/getMovieTypes?filename="..getCurrentFile().."&time="..getFormatedTime())
    
    if(string.find(res, "movie types")) then
        -- strip any unneeded information
        vlc.osd.message(res.sub(res, string.find(res, "movie type"), string.len(res)))
    else
        vlc.osd.message("An error occured - probably no start time set yet")		
    end
end

function getRating()
    vlc.msg.dbg("getRating: "..getFormatedTime())
    local res = get("http://localhost:7679/api/v1/getRating?filename="..getCurrentFile().."&time="..getFormatedTime())

    if(string.find(res, "rating: ")) then
        -- strip any unneeded information
        vlc.osd.message(res.sub(res, string.find(res, "rating: ") + 8, string.len(res)))
    else
        vlc.osd.message("An error occured - probably no start time set yet")		
    end

end



function setRating()
    dlg = vlc.dialog("Set rating")
    input_wgt = dlg:add_text_input("", 1,1,8,1)
    w3 = dlg:add_button("Save rating!",click_rating_Action, 1, 3, 1, 1)
    vlc.osd.message(input_wgt:get_text())
end

function click_rating_Action()
    vlc.msg.dbg("saving rating")
    local input_string = input_wgt:get_text()  -- local variable
    vlc.msg.dbg("done saving rating")
    vlc.osd.message(input_string)
    vlc.msg.dbg("really done rating immersion"..input_string)
        input_string = 		 string.gsub(input_string, '+', '%%2B')

    local res = get("http://localhost:7679/api/v1/setRating?filename="..getCurrentFile().."&time="..getFormatedTime().."&rating="..input_string)

    dlg:delete()
end



function getImmersion()
    vlc.msg.dbg("getImmersion: "..getFormatedTime())
    local res = get("http://localhost:7679/api/v1/getImmersion?filename="..getCurrentFile().."&time="..getFormatedTime())

    if(string.find(res, "immersion: ")) then
        -- strip any unneeded information
        vlc.osd.message(res.sub(res, string.find(res, "immersion: ") + 11, string.len(res)))
    else
        vlc.osd.message("An error occured - probably no start time set yet")		
    end
end


function setImmersion()
    dlg = vlc.dialog("Set immersion")
    input_wgt = dlg:add_text_input("", 1,1,8,1)
    w3 = dlg:add_button("Save immersion!",click_immersion_Action, 1, 3, 1, 1)
    vlc.osd.message(input_wgt:get_text())
end

function click_immersion_Action()
    vlc.msg.dbg("saving immersion")
    local input_string = input_wgt:get_text()  -- local variable
    vlc.msg.dbg("done saving immersion")
    vlc.osd.message(input_string)
    vlc.msg.dbg("really done saving immersion"..input_string)
    input_string = 		 string.gsub(input_string, '+', '%%2B')

    local res = get("http://localhost:7679/api/v1/setImmersion?filename="..getCurrentFile().."&time="..getFormatedTime().."&immersion="..input_string)

    dlg:delete()
end

--function selectInList()
--	vlc.msg.dbg("select in list")
--	get("http://localhost:7679/api/v1/selectInList?filename="..getCurrentFile().."&time="..getFormatedTime())
--end

function getTimePassed()
    if (vlc.object.input() == nil) then
	return -1
    else
        return vlc.var.get(vlc.object.input(), "time")
    end
end


function input_changed()
   -- related to capabilities={"input-listener"} in descriptor()
   -- triggered by Start/Stop media input event
   vlc.msg.dbg("input changed " .. vlc.playlist.status())
end

function playing_changed()
   -- related to capabilities={"playing-listener"} in descriptor()
   -- triggered by Pause/Play madia input event
	vlc.msg.dbg("playing changed " .. vlc.playlist.status())
end

function meta_changed()
	vlc.msg.dbg("meta changed " .. vlc.playlist.status())
end