httpd = require 'httpd'
math = require 'math'
sqlite = require 'sqlite'

cities = {"London", "Manchester", "Birmingham", "Leeds", "Glasgow", "Southampton", "Liverpool", "Newcastle", "Nottingham", "Sheffield", "Bristol", "Belfast", "Leicester"}

weather_desc = {"sunny", "cloudy", "partially cloudy", "rainy", "snowy"}


function valid_city(cities, city)
    for i, v in ipairs(cities) do
        if v == city
        then
            return true
        end
    end
    return false
end


function forecast(env, headers, query)
    if query and query["city"]
    then
        local city = query["city"]
        if city == "list"
        then 
            httpd.write("HTTP/1.1 200 Ok\r\n")
            httpd.write("Content-Type: application/json\r\n\r\n")
            httpd.write('{"code": 200,')
            httpd.write('"cities": [')
            for k,v in pairs(cities) do
                httpd.write('"' .. v .. '"')
                if k < #cities
                then
                    httpd.write(',')
                end
            end
            httpd.write(']}')
        elseif not valid_city(cities, city)
        then
            -- city=London') os.execute('id') --
            httpd.write("HTTP/1.1 500 Error\r\n")
            httpd.write("Content-Type: application/json\r\n\r\n")
            local json = string.format([[
                httpd.write('{"code": 500,')
                httpd.write('"error": "unknown city: %s"}')
            ]], city)

            load(json)()
        else
            -- just some fake weather data
            weather_data = {
                {
                    ["date"] = os.date("%Y-%m-%d", os.time()),
                    ["desc"] = weather_desc[math.random(#weather_desc)],
                    ["tempmin"] = math.random(30),
                    ["tempmax"] = math.random(30,50),
                    ["pressure"] = math.random(1000,2000),
                    ["humidity"] = math.random(0,100),
                    ["windspeed"] = math.random() + math.random(4),
                    ["winddegree"] = math.random() + math.random(364),
                },
                {
                    ["date"] = os.date("%Y-%m-%d", os.time()+86400),
                    ["desc"] = weather_desc[math.random(#weather_desc)],
                    ["tempmin"] = math.random(30),
                    ["tempmax"] = math.random(30,50),
                    ["pressure"] = math.random(1000,2000),
                    ["humidity"] = math.random(0,100),
                    ["windspeed"] = math.random() + math.random(4),
                    ["winddegree"] = math.random() + math.random(364),
                },
                {
                    ["date"] = os.date("%Y-%m-%d", os.time()+86400*2),
                    ["desc"] = weather_desc[math.random(#weather_desc)],
                    ["tempmin"] = math.random(30),
                    ["tempmax"] = math.random(30,50),
                    ["pressure"] = math.random(1000,2000),
                    ["humidity"] = math.random(0,100),
                    ["windspeed"] = math.random() + math.random(4),
                    ["winddegree"] = math.random() + math.random(364),
                },
                {
                    ["date"] = os.date("%Y-%m-%d", os.time()+86400*3),
                    ["desc"] = weather_desc[math.random(#weather_desc)],
                    ["tempmin"] = math.random(30),
                    ["tempmax"] = math.random(30,50),
                    ["pressure"] = math.random(1000,2000),
                    ["humidity"] = math.random(0,100),
                    ["windspeed"] = math.random() + math.random(4),
                    ["winddegree"] = math.random() + math.random(364),
                },
                {
                    ["date"] = os.date("%Y-%m-%d", os.time()+86400*4),
                    ["desc"] = weather_desc[math.random(#weather_desc)],
                    ["tempmin"] = math.random(30),
                    ["tempmax"] = math.random(30,50),
                    ["pressure"] = math.random(1000,2000),
                    ["humidity"] = math.random(0,100),
                    ["windspeed"] = math.random() + math.random(4),
                    ["winddegree"] = math.random() + math.random(364),
                },
            }

            httpd.write("HTTP/1.1 200 Ok\r\n")
            httpd.write("Content-Type: application/json\r\n\r\n")

            local json = string.format([[
                httpd.write('{"code": 200,')
                httpd.write('"city": "%s",')
                httpd.write('"list": [')
            ]], city)
            load(json)()

            for i = 1, #weather_data - 1
            do
                local json = string.format([[
                    httpd.write('{"date": "%s",')
                    httpd.write('"weather": {')
                    httpd.write('"description": "%s",')
                    httpd.write('"temperature": {')
                    httpd.write('"min": "%s",')
                    httpd.write('"max": "%s"},')
                    httpd.write('"pressure": "%s",')
                    httpd.write('"humidity": "%s",')
                    httpd.write('"wind": {')
                    httpd.write('"speed": "%s",')
                    httpd.write('"degree": "%s"}}},')
                ]],
                    weather_data[i]["date"],
                    weather_data[i]["desc"],
                    weather_data[i]["tempmin"],
                    weather_data[i]["tempmax"],
                    weather_data[i]["pressure"],
                    weather_data[i]["humidity"],
                    weather_data[i]["windspeed"],
                    weather_data[i]["winddegree"])

                load(json)()
            end

            local json = string.format([[
                httpd.write('{"date": "%s",')
                httpd.write('"weather": {')
                httpd.write('"description": "%s",')
                httpd.write('"temperature": {')
                httpd.write('"min": "%s",')
                httpd.write('"max": "%s"},')
                httpd.write('"pressure": "%s",')
                httpd.write('"humidity": "%s",')
                httpd.write('"wind": {')
                httpd.write('"speed": "%s",')
                httpd.write('"degree": "%s"}}}]}')
            ]],
                weather_data[#weather_data]["date"],
                weather_data[#weather_data]["desc"],
                weather_data[#weather_data]["tempmin"],
                weather_data[#weather_data]["tempmax"],
                weather_data[#weather_data]["pressure"],
                weather_data[#weather_data]["humidity"],
                weather_data[#weather_data]["windspeed"],
                weather_data[#weather_data]["winddegree"])

            load(json)()
        end 
    else
        httpd.write("HTTP/1.1 200 Ok\r\n")
        httpd.write("Content-Type: application/json\r\n\r\n")
        httpd.print('{"code": 200, "message": "No city specified. Use \'city=list\' to list available cities."}')
    end
end

httpd.register_handler('forecast', forecast)
