require("math")
JSON = (loadfile "JSON.lua")() 

function split(inputstr, sep)
        if sep == nil then
                sep = "%s"
        end
        t={} ; i=1
        for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
                t[i] = str
                i = i + 1
        end
        return t
end

function tableLen(T)
  local count = 0
  for _ in pairs(T) do count = count + 1 end
  return count
end

 function filter(func, tbl)
     local newtbl= {}
     for i,v in pairs(tbl) do
         if func(v) then
	     newtbl[i]=v
         end
     end
     return newtbl
 end

--v1 greate than v2
function cmpVer(v1,v2)
 if v1==v2 then
   return 0
  end
  local a1=split(v1,".")
  local a2=split(v2,".")
  local len1=tableLen(a1)
  local len2=tableLen(a2)
  local min=math.min(len1,len2)
  local count=0
  for i=1,min  do
    local cmp= (tonumber(a1[i])-tonumber(a2[i]))
    if cmp>0 then
      return 1
    elseif cmp<0 then
      return -1
    end;
  end
  return false
end

function GetUpdateInfo(str,product,curVer)
  local result=nil
  local json=str
  local infoList=JSON:decode(json)
  --compare algorth
  function cmpAlg(a,b) return cmpVer(a.ver,b.ver)>0 end
  function isProduct(a) return a.product==product end
  infoList=filter(isProduct,infoList)
  table.sort(infoList,cmpAlg)
  
  for idx,v in ipairs(infoList) do
    if cmpVer(v.ver,curVer)>0 and cmpVer(v.miniVer,curVer)<=0 then
      result=v
      break
    end
  end
  return result
end

function test()
    local f=io.open("test.json")
    local json=f:read("*all")
    local infoList=JSON:decode(json)
    local ver=GetUpdateInfo(json,"iflybook","1.0.0.1")
    if   ver then
      print(ver.ver)
    end
    
end
--test()


