import Vapor
import Foundation
import Leaf

func routes(_ app: Application) throws {
    // Render home page when root domain is loaded
    app.get { req  -> EventLoopFuture<View> in
        let fileData = try String(contentsOfFile: "\(app.directory.resourcesDirectory)/config.json").data(using: .utf8)
        let config: Config = try! JSONDecoder().decode(Config.self, from: fileData!)
        return req.view.render("home", ["config": config])
    }

    app.get("status", ":url") { req -> EventLoopFuture<[String: String]> in
        let url = URL(string: req.parameters.get("url")!)
        return req.client.get("https://isitdown.site/api/v3/\(url!)").flatMapThrowing { res in
            try res.content.decode(isItUp.self)
        }.map { json in
            ["down": String(json.isitdown), "code": String(json.response_code)]
        }
    }
}
