local array = require("database.array")
local flatdb = require('database.flatdb')
local date = require('date')
local db = flatdb(ngx.var.document_root..'/database')

local _M = {}

_M.cellar = {}

_M.weather = {}

_M.room = {}

if not db.cellar then 
	db.cellar = {{temp=0, date = os.date('%Y-%m-%d %H:%M:%S'), warm=0, warm_status='is-danger',temp_status='is-warning'}} 
	db:save()
end

if not db.weather then 
	db.weather = {{temp=0, date = os.date('%Y-%m-%d %H:%M:%S'), warm=0, warm_status='is-success',temp_status='is-success'}} 
	db:save()
end

if not db.room then 
	db.room = {{temp=0, date = os.date('%Y-%m-%d %H:%M:%S'), warm=0, warm_status='is-danger',temp_status='is-warning'}} 
	db:save()
end

function _M.cellar.now()
	return db.cellar[#db.cellar]
end

function _M.cellar.data(start,ends)
	if not start then start = date(start) else start = date():addhours(-24) end
	if not ends then ends = date(ends) else ends = date() end
	local res = {}
	for key,val in pairs(db.cellar) do
		if date(val.date) >= start and date(val.date) <= ends then
			table.insert(res,val)
		end
	end
	return res
end

function _M.weather.now()
	return db.weather[#db.weather]
end

function _M.weather.data(start,ends)
	if not start then start = date(start) else start = date():addhours(-24) end
	if not ends then ends = date(ends) else ends = date() end
	local res = {}
	for key,val in pairs(db.weather) do
		if date(val.date) >= start and date(val.date) <= ends then
			table.insert(res,val)
		end
	end
	return res
end

function _M.room.now()
	return db.room[#db.room]
end

function _M.room.data(start,ends)
	if not start then start = date(start) else start = date():addhours(-24) end
	if not ends then ends = date(ends) else ends = date() end
	local res = {}
	for key,val in pairs(db.room) do
		if date(val.date) >= start and date(val.date) <= ends then
			table.insert(res,val)
		end
	end
	return res
end

return _M
