package controllers

import javax.inject._
import play.api.mvc._

import models.{Daily}

import scala.concurrent.TimeoutException
import org.bson.types.ObjectId

/**
 * This controller handles all the Daily endpoints.
 */
@Singleton
class DailyController @Inject()(val controllerComponents: ControllerComponents) extends BaseController {

  /**
   * Create an Action to fetch all the Dailies in the DB.
   */
  def getAll() = Action {
    println("DailyController:getAll")

    try {
        val result: Seq[Daily] = Daily.getAllDailiesAsync()
        val jsonResult = Daily.toJson(result)
        Ok(jsonResult)
    } catch {
        case _: TimeoutException => BadRequest("Request timed out")
        case _: Throwable => BadRequest("Exception raised")
    }
  }

  /**
   * Create an Action to fetch the user's Dailies in the DB.
   */
  def getUserDailies() = Action {
    println("DailyController:getUserDailies")

    try {
        val result: Seq[Daily] = Daily.getUserDailiesAsync(new ObjectId("641128f7e80bcd1ba39d04af"))
        val jsonResult = Daily.toJson(result)
        Ok(jsonResult)
    } catch {
        case _: TimeoutException => BadRequest("Request timed out")
        case _: Throwable => BadRequest("Exception raised")
    }
  }

  /**
   * Create an Action to fetch the user's Feed.
   */
  def getUserFeed() = Action {
    println("DailyController:getUserFeed")

    try {
        val result: Seq[Daily] = Daily.getUserFeedAsync(new ObjectId("641128f7e80bcd1ba39d04ae"))
        val jsonResult = Daily.toJson(result)
        Ok(jsonResult)
    } catch {
        case _: TimeoutException => BadRequest("Request timed out")
        case _: Throwable => BadRequest("Exception raised")
    }
  }

  def create() = Action {
    println("DailyController:create")

    try {
        // Dummy data
        val result = Daily.createDailyAsync(new ObjectId("641128f7e80bcd1ba39d04ae"), new ObjectId("641128f7e80bcd1ba39d04ae"), "asddas")
        val jsonResult = Daily.toJson(result)
        Ok(jsonResult)
    } catch {
        case _: TimeoutException => BadRequest("Request timed out")
        case _: Throwable => BadRequest("Exception raised")
    }
  }

  def like() = Action {
    println("DailyController:like")

    try {
        // Dummy data
        Daily.likeAsync(new ObjectId("642314b4b9748f6794e9895b"), new ObjectId("641128f7e80bcd1ba39d04ae"))
        Ok("Updated")
    } catch {
        case _: TimeoutException => BadRequest("Request timed out")
        case _: Throwable => BadRequest("Exception raised")
    }
  }
}