import Vapor

/// Register your application's routes here.
public func routes(_ router: Router) throws {
    // Basic "It works" example
    router.get { req in
        return "It works!"
    }

    // Example of configuring a controller
    let orderController = OrderController()
    router.get("orders", use: orderController.index)
    router.post("order", use: orderController.create)
    
    router.get("order", Order.parameter, "ship") { req -> Future<Response> in
        return try req.parameters.next(Order.self).flatMap { order in
            return order.delete(on: req).map(to: Response.self) {
                return req.redirect(to: "/orderFulfillment")
            }
        }
    }
    
    
    router.get("orderFulfillment") { req -> Future<View> in
        struct OrderFulfillmentContext: Codable {
            let order: Order
            let verboseAddress: String
            let cupcakeType: String
            let specialRequests: String
            
            init(order: Order) {
                self.order = order
                verboseAddress = "\(order.name) - \(order.streetAddress) \(order.city) \(order.zip)"
                cupcakeType = Order.types[order.type]
                var specialRequests = ""
                if order.addSprinkles {
                    specialRequests += "Add sprinkles    "
                }
                if order.extraFrosting {
                    specialRequests += "Extra Frosting"
                }
                self.specialRequests = specialRequests
            }
        }
        
        return try orderController.index(req).flatMap(to: View.self) { orders in
            let orderFulfillmentContexts = orders.map { order in
                OrderFulfillmentContext(order: order)
            }
            return try req.view().render("OrderFulfillment", ["orders": orderFulfillmentContexts])
        }
    }
}
