local zlib = require "zlib"
local cjson = require "cjson"

local function set_data(str,proj,ptype,ngx)
    local s = string.sub(str,0,1)
    local headers = ngx.req.get_headers()
    local ip = headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr or "0.0.0.0"

    if s == "{" then
       str=string.gsub(str,'{','{"proj":"'..proj..'","ptype":"'..ptype..'","ip":"'..ip..'",',1)
       --  str=str:gsub('\\\\', ''):gsub('\\', '_',1):gsub('\\','/')
       --  str = "["..str.."]"
    end
    ngx.var.data=str
end

local function set_list_data(listStr,proj,ptype)
    -- local list= cjson.decode(listStr)
    -- ngx.var.data=listStr
    -- ngx.log(ngx.INFO,"std1")


    local s = string.sub(listStr,0,1)
    local headers = ngx.req.get_headers()
    local ip = headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr or "0.0.0.0"

    if s == "[" then
        listStr=string.gsub(listStr,'%[','')
        listStr=string.gsub(listStr,'%]','')
        listStr=string.gsub(listStr,'(%,?){"distinct_id"','\n{"ip":"'..ip..'","proj":"'..proj..'","ptype":"'..ptype..'","distinct_id"')
    end
    ngx.var.data=listStr
end

local req_args = ngx.req.get_uri_args()
local proj=req_args["project"]
local ptype=req_args["ptype"]
if proj ==nil then
  ngx.say("{\"r\":\"err\",\"msg\",\"no project\"}")
  return
end

if ptype ==nil then
    ptype=""
end

local method=ngx.req.get_method()
if method == "POST" then
   ngx.req.read_body()
   local body = ngx.req.get_post_args()

   local data_list = body["data_list"]
   if data_list then
        local listStr= ngx.decode_base64(data_list)
        set_list_data(listStr,proj,ptype)
   end
   local data = body["data"]
   if data then
        local dec= ngx.decode_base64(data)
        set_data(dec,proj,ptype,ngx)
   end
elseif  method == "GET" then
    -- ngx.var.data="get lai le"
     local args = ngx.req.get_uri_args()
     local data = args["data"]
     if data then
        local dec= ngx.decode_base64(data)
        --ngx.var.data=dec
        set_data(dec,proj,ptype,ngx)
     end
end
ngx.say("success")
