package com.eddsteel.posts.leastpower
package endpoints
import model._
import services._
import webapp.{Request, Response, NotFoundException}
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try
import java.time.{LocalDateTime, LocalDate}
trait EndpointsV3 {
this: UserServiceComponent with GiftServiceComponent =>
import EndpointsV3._
def postGift(req: Request)(implicit ec: ExecutionContext): Future[Response] = {
val response = for {
userId <- Future.fromTry(WebApp.extractAndValidateUserId(req))
maybeUser <- userService.getById(userId)
user = maybeUser.getOrElse(throw NotFoundException(userId))
gift <- maybeSendGift(user.id, user.birthday, user.favoriteThing,
LocalDateTime.now, giftService.order)
response <- Future.fromTry(WebApp.mkResponse(gift))
} yield response
response.recover(WebApp.mkErrorResponse)
}
}
object EndpointsV3 {
def isToday(birthday: LocalDate, now: => LocalDateTime) =
now.getDayOfMonth == birthday.getDayOfMonth &&
now.getMonth == birthday.getMonth
def maybeSendGift(userId: ID, birthday: LocalDate, favoriteThing: String,
now: => LocalDateTime,
orderGift: (Long, String) => Future[(String, Option[Long])])
(implicit ec: ExecutionContext) = {
val birthdayToday = isToday(birthday, now)
if (birthdayToday) orderGift(userId, favoriteThing)
else Future.successful(("not today", None))
}
}