#!/usr/bin/lua

local json = require("json")
local socket = require("socket")
local http = require("socket.http")

require "wm_util"

function getConfig(configname)

  local command,f

  local uci=require("uci")
  local cur=uci.cursor()
  local config
  if configname then
    config=configname
  else
    config="weathermon"
  end

  web_url  = cur.get(config,"web","url")
  web_user = cur.get(config,"web","user")
  web_timeout = cur.get(config,"web","timeout")
  web_pass = cur.get(config,"web","password")
 
  if not web_timeout then
    web_timeout = 10
  end

  backlogdb = cur.get(config,"process","backlogdb")

end

function submitValue(timestamp,type,id,param,val)

  local url = web_url.."?stype="..url_encode(type).."&sid="..url_encode(id).."&param="..url_encode(param).."&value="..url_encode(val).."&time="..url_encode(timestamp)

  if web_user then
    url = url:gsub("//","//"..web_user..":"..web_pass.."@",1)
  end

  local result,code = http.request ({
    url=url, create=function()
      local req_sock = socket.tcp()
      req_sock:settimeout(web_timeout)
      return req_sock
    end})

  if code ~= 200 then
    return false
  end

  return true

end

getConfig(arg[1])

if backlogdb then

  local dbdriver = require "luasql.sqlite3"
  env = assert(dbdriver.sqlite3())
  if file_exists(backlogdb) then
    backlog_con = assert(env:connect(backlogdb))
  end

  cursor = assert(backlog_con:execute("SELECT rowid,time_stamp,sensor_id,sensor,param,value FROM queue LIMIT 400"))
  row = cursor:fetch ({}, "a")
  while row do
    if submitValue(row.time_stamp,row.sensor,row.sensor_id,row.param,row.value) then
      backlog_con:execute(string.format("DELETE FROM queue WHERE rowid='%s'",row.rowid))
    end
    row = cursor:fetch (row, "a")
  end

end