do

local makeOurDate = function(dateString)
  local pattern = "(%d+)%-(%d+)%-(%d+)"
  local year, month, day = dateString:match(pattern)
  if month == "00" then
    return year
  elseif day == "00" then
    return month..'.'..year
  else
    return day..'.'..month..'.'..year
  end
end

local function get_plex(query)
  local token = cred_data.plex_token
  local baseurl = 'http://kyouko.local:32400' --replace it with yours
  local response_body = {}
  local request_constructor = {
      url = baseurl..'/search?query='..query..'&X-Plex-Token='..token,
      method = "GET",
      sink = ltn12.sink.table(response_body),
      headers = {
        Accept = "application/json"
      }
   }
local ok, response_code, response_headers, response_status_line = http.request(request_constructor)
local data = json:decode(table.concat(response_body))._children[1]
	
	local title = data.title
	
	if data.tagline then
	tag = '\n"'..data.tagline..'"'
	else
	tag = ''
	end
	
	if data.parentIndex then
	season = 'S'..convertNumbers(data.parentIndex)
	else
	season = ''
	end
	
	if data.index then
	episode = 'E'..convertNumbers(data.index)
	else
	episode = ''
	end
	
	if data.grandparentTitle then
	from = ' (aus '..data.grandparentTitle..' ['..string.gsub(season..episode, 'S0E', 'SP')..']'..') '
	else
	from = ''
	end
	
	if data.originalTitle then
	origtitle = '\nOriginal: '..data.originalTitle
	else
	origtitle = ''
	end
	
	if data.studio then
	studio = '\nStudio: '..data.studio
	else
	studio = ''
	end
	
	if data.originallyAvailableAt then
	date = '\nAusstrahlung: '..makeOurDate(data.originallyAvailableAt)
	elseif data.year then
	date = '\nAusstrahlung: '..data.year
	else
	date = ''
	end
	
	if data.leafCount then
	episodes = ' ('..data.leafCount..' Episoden) '
	else
	episodes = ''
	end
	
	if data.contentRating then
	fsk = '\nAltersfreigabe: '..gerRating(data.contentRating)
	else
	fsk = ''
	end
	
	if data.duration then
	duration = '\nLänge: '..formatMilliseconds(data.duration)
	else
	duration = ''
	end
	
	if data.rating then
	rating = '\nBewertung: '..data.rating
	else
	rating = ''
	end
	
	if data.summary then
	desc = '\n\n'..string.gsub(unescape(data.summary), 'EditBackgroundNo(.*)', '')
	else
	desc = ''
	end
	
	if data.thumb then
	pic = baseurl..data.thumb
	end

	local text = title..tag..from..origtitle..studio..date..episodes..fsk..duration..rating..desc..'\n'

	
	if data.thumb then
	return text, pic
	else
	return text
	end
    
end

local function run(msg, matches)
  local query = string.gsub(URL.escape(matches[1]), '&', '+')
  local text, pic = get_plex(query)
  local receiver = get_receiver(msg)
  local file = download_to_file(pic)
    send_photo(receiver, file, ok_cb, false)
  return text
end

return {
  description = "Suche für Plex Media Server", 
  usage = "#plex [BEGRIFF]",
  patterns = {"^#[Pp][Ll][Ee][Xx] (.*)$"},
  run = run 
}

end
