local playstation_store = {}

playstation_store.triggers = {
  'store.playstation.com/#!/([A-Za-z]+)%-([A-Za-z]+)/.*/cid=(.+)',
  'store.sonyentertainmentnetwork.com/#!/([A-Za-z]+)%-([A-Za-z]+)/.*/cid=(.+)'
}

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

function playstation_store:get_info(country_code, game_id)
  local url = 'https://store.playstation.com/store/api/chihiro/00_09_000/container/'..country_code..'/999/'..game_id
  local res, code = https.request(url)
  if code ~= 200 then return nil end
  local data = json.decode(res)
  if not data then return nil end
 
  local title = data.name
  if data.provider_name then
    publish = ' von '..data.provider_name
  else
    publish = ''
  end
  if data.playable_platform then
    system = ' für '..data.playable_platform[1]
  else
    system = ''
  end
  if data.gameContentTypesList then
    types = ' ['..data.gameContentTypesList[1].name..']'
  else
    types = ''
  end
  if data.skus then
  if data.skus[1].rewards[1] then
  
  --[[
  if data.skus[1].rewards[1].isPlus ~= true then
	psplus = ''
  else
	psplus = ' PS+ Exklusiv!'
  end
  ]]
	
    price = data.skus[1].rewards[1].display_price..' statt '..data.default_sku.display_price..' (Spare '..data.skus[1].rewards[1].discount..'%)'--..psplus
  else
    price = data.default_sku.display_price--..psplus
  end
  else
    price = 'N/A'
  end
  local fsk = data.age_limit
  local description = string.sub(unescape(data.long_desc:gsub("%b<>", "")), 1, 300)..'...'
  local release = makeOurDate(data.release_date)
  if data.images[4].type ~= 10 then
    image_url = data.images[4].url
  else
    image_url = data.images[1].url
  end
  
  local text = '<b>'..title..'</b>'..publish..system..types..'\n<b>Preis:</b> '..price..'\n<b>Freigegeben ab:</b> '..fsk..'\n'..'<b>Release:</b> '..release..'\n\nBeschreibung:\n<i>'..description..'</i>'
 
  return text, image_url
end

function playstation_store:action(msg, config, matches)
  local country_code = string.upper(matches[2])..'/'..matches[1]
  local game_id = matches[3]
  local text, image_url = playstation_store:get_info(country_code, game_id)
  if not text then
    utilities.send_reply(msg, chat, config.errors.result)
	return
  end
  if image_url then
	utilities.send_typing(msg.chat.id, 'upload_photo')
    utilities.send_photo(msg.chat.id, image_url, nil, msg.message_id)
  end
  utilities.send_reply(msg, text, 'HTML')
end

return playstation_store