app.net={}

function make(con,payload)
  payload=string.gsub(payload,app.global.package,'')
  print('from tcp',payload)
  if payload == app.global.heartTag then
    return
  end
  local ok,param=pcall(sjson.decode,payload)
  if(ok)then 
    local fun=app.route[param['path']]
    if(fun ~= nil)then
      local data=fun(param)
      app.net.send(data)
    else
      print('not find route')
    end
  end 
end



srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
  conn:on("receive",function(conn,payload)
    local resultStrList =app.global.split(payload,'\n')
    resultStrList=app.global.split(resultStrList[1],'?')
    resultStrList=app.global.split(resultStrList[2],' ')
    resultStrList=app.global.split(resultStrList[1],'&')

    local param={}
    for i,v in pairs(resultStrList) do
      local par=app.global.split(v,'=')
      param[par[1]]=par[2]
    end

    local htmlStr
    local fun=app.route[param['path']]
    if(fun ~= nil)then
      htmlStr=fun(param)
    else
      local fun=app.route['webIndex']
      if(fun ~= nil)then
        htmlStr=fun(param)
      else
        htmlStr="<h1> Hello, SMART!!! </h1>"
      end
    end

    local html = "HTTP/1.0 200 OK\r\n"
    .."Content-Type: application/json\r\n"
    .."Access-Control-Allow-Origin: *\r\n"
    .."Connection: Close\r\n\r\n"
    ..htmlStr

    conn:send(html)

  end)
  conn:on("sent",function(conn) conn:close() end)
end)

local conn=net.createConnection(net.TCP) 
app.net.connS=true
conn:on("receive", function(con, payload) 
  make(conn,payload)
end)

conn:on("disconnection", function(con, payload)
  app.net.connS=true
end)

conn:on("connection", function(con, payload)
  if(app.route.init ~= nil)then 
    if(app.config.cloudUser ~= '')then
      if(app.config.devmes == '未注册，到服务器')then 
        app.net.send(app.route.regDev())
      else
        app.net.send(app.route.init())
      end
    end
  end
  app.net.connS=false
  print('[notice] connect success',app.config['serverUrl'],app.config['serverPort'])
end)

app.net.con=function(tag)
  if(not app.wifi.stat or tag%2 ~= 1)then
    return
  end
  if(app.net.connS)then
    pcall(function()
      conn:connect(app.config['serverPort'],app.config['serverUrl'])
      print('[notice] await connect ',app.config['serverUrl'],app.config['serverPort'])
    end)
  else
    app.net.send(app.global.heartTag)
  end
end

app.net.send=function(data)
  if(data ~= nil)then
    local ok,param=pcall(function()
      conn:send(data..app.global.package)
    end)
    if(ok)then 
      print('[notice] send success',data)
    else
      print('[notice] send false',data)
    end   
  end
end
