--[[
 * Copyright (C) 2014 Bastien Nocera
 *
 * Contact: Bastien Nocera <hadess@hadess.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
--]]

BBCNEWS_ROOT_URL          = 'http://www.bbc.co.uk/moira/feeds/iphone/news/en-GB/v1'
BCCNEWS_AGENT             = 'BBC News 1.7.1 (iPhone; iPhone OS 4.0.1; en_GB)'

netopts = {
	user_agent = 'BBC News 1.7.1 (iPhone; iPhone OS 4.0.1; en_GB)',
	cache = true,
	cache_size = 15 * 1024,
	throttling = 15,
}

---------------------------
-- Source initialization --
---------------------------

source = {
  id = "grl-bbcnews-lua",
  name = "BBC News",
  description = "A source for browsing videos from BBC News",
  supported_keys = { "id", "thumbnail", "title", "url", "type" },
}

------------------
-- Source utils --
------------------

function grl_source_browse(media_id)
  if grl.get_options("skip") > 0 then
    grl.callback()
  else
    if not media_id then
      grl.fetch(BBCNEWS_ROOT_URL, "bbcnews_root_fetch_cb", netopts)
    else
      print ("fetching " .. media_id)
      grl.fetch(media_id, "bbcnews_fetch_cb", netopts)
    end
  end
end

------------------------
-- Callback functions --
------------------------

-- return all the categories found
function bbcnews_root_fetch_cb(results)
  local json = {}

  json = grl.lua.json.string_to_table(results)
  if not json or json.stat == "fail" or not json.feeds[1].feeds then
    grl.callback()
    return
  end

  for index, item in pairs(json.feeds[1].feeds) do
    local media = {}
    media.type = 'box'
    media.id = item.feed_url
    media.title = item.title

    grl.callback(media, -1)
  end
  grl.callback()
end

-- return all the items in a category
function bbcnews_fetch_cb(results)
  local json = {}

  print ("bbcnews_fetch_cb")

  -- FIXME
  -- parse the XML...
end

-------------
-- Helpers --
-------------

function create_media(item)
  local media = {}

  media.type = "video"
  media.id = item.id
  media.url = item.webUrl
  media.title = item.webTitle
  media.thumbnail = item.fields.thumbnail

  return media
end
