/*
 * Copyright (C) 2020  Prasoon Joshi
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package controllers

import java.util.UUID
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._

import models._

import javax.inject._
import play.api.libs.json.{JsObject, JsString, JsValue, Json, JsError}
import play.api.mvc._
import play.api.libs.ws._

import graphql.GraphqlService
import graphql.SchemaInputObjects.IngestWithCrosswalk
import repository.GremlinServer

/**
 * This controller creates an `Action` to handle HTTP requests to the
 * application's home page.
 */
//@Singleton
class HomeController (graphqlService: GraphqlService,
  cc: ControllerComponents,
  gremlinServer: GremlinServer) extends AbstractController(cc) {

    //def entity[E <: NiosxEntity](id: String) = Action.async {
    //  ???
    //}

    // --- GraphQL section
    import scala.concurrent.ExecutionContext.Implicits.global
  
    def parseVariables(vars: String) =
      if (vars.trim == "" || vars.trim == "null") Json.obj() else 
      Json.parse(vars).as[JsObject]

  
    def graphQl = Action.async(parse.json) { implicit  request: Request[JsValue] =>

      val userToken: Option[String] =
        request.headers.get(AUTHORIZATION).map(
          s => s.replaceFirst("Bearer","").strip)
      import scala.concurrent.ExecutionContext.Implicits.global
      graphqlService.fetchQueryResult(userToken, request.body)
    }

    import sangria.renderer.SchemaRenderer
    import graphql.SchemaDefinition
    def graphqlSchema = Action { implicit request: Request[AnyContent] => 
      Ok(SchemaRenderer.renderSchema(SchemaDefinition.schema))
    }
    def graphMl = Action { implicit request: Request[AnyContent] =>
      //TODO: Don't call the GremlinServer directly. Request from a service.
      // Repair the wiring in places for HomeController accordingly.
      Ok(gremlinServer.graphMl)
    }

    /*
    def ingestWithCrosswalk = Action(parse.json) {
      implicit request =>
        val result = request.body.validate[IngestWithCrosswalk]
        result.fold(
          errors => {
            BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson(errors)))
          },
          obj => {
            val docRequest = ws.url(obj.url)
            val docXml: Future[WSResponse] = docRequest.get()
            Ok(Json.obj("status" -> "OK", 
              "message" -> "Your document is available at <id>",
              "xml" -> "eves")
            )
          }
        )
    }
    */


}
