<commit_before>package controllers

import com.google.inject.Inject
import models.AcquireCompletionViewModel
import models.CompleteAndConfirmFormModel
import models.CompleteAndConfirmViewModel
import models.NewKeeperDetailsViewModel
import models.VehicleLookupFormModel
import models.VehicleTaxOrSornFormModel
import models.CompleteAndConfirmFormModel.Form.{MileageId, ConsentId}
import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import play.api.data.{FormError, Form}
import play.api.mvc.{Action, AnyContent, Call, Controller, Request, Result}
import play.api.Logger
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import uk.gov.dvla.vehicles.presentation.common
import common.clientsidesession.ClientSideSessionFactory
import common.clientsidesession.CookieImplicits.{RichCookies, RichForm, RichResult}
import common.mappings.TitleType
import common.model.{VehicleDetailsModel, TraderDetailsModel}
import common.services.DateService
import common.views.helpers.FormExtensions.formBinding
import utils.helpers.Config
import views.html.acquire.complete_and_confirm
import webserviceclients.acquire.AcquireRequestDto
import webserviceclients.acquire.AcquireResponseDto
import webserviceclients.acquire.AcquireService
import webserviceclients.acquire.KeeperDetailsDto
import webserviceclients.acquire.TitleTypeDto
import webserviceclients.acquire.TraderDetailsDto

class CompleteAndConfirm @Inject()(webService: AcquireService)(implicit clientSideSessionFactory: ClientSideSessionFactory,
                                                               dateService: DateService,
                                                               config: Config) extends Controller {

  private[controllers] val form = Form(
    CompleteAndConfirmFormModel.Form.Mapping
  )

  private final val NoCookiesFoundMessage = "Failed to find new keeper details and or vehicle details and or " +
    "vehicle sorn details in cache. Now redirecting to vehicle lookup"

  def present = Action { implicit request =>
    val newKeeperDetailsOpt = request.cookies.getModel[NewKeeperDetailsViewModel]
    val vehicleDetailsOpt = request.cookies.getModel[VehicleDetailsModel]
    val vehicleSornOpt = request.cookies.getModel[VehicleTaxOrSornFormModel]
    (newKeeperDetailsOpt, vehicleDetailsOpt, vehicleSornOpt) match {
      case (Some(newKeeperDetails), Some(vehicleDetails), Some(vehicleSorn)) =>
        Ok(complete_and_confirm(CompleteAndConfirmViewModel(form.fill(), vehicleDetails, newKeeperDetails, vehicleSorn), dateService))
      case _ => redirectToVehicleLookup(NoCookiesFoundMessage)
    }
  }

  def submit = Action.async { implicit request =>
    form.bindFromRequest.fold(
      invalidForm => Future.successful {
        val newKeeperDetailsOpt = request.cookies.getModel[NewKeeperDetailsViewModel]
        val vehicleDetailsOpt = request.cookies.getModel[VehicleDetailsModel]
        val vehicleSornOpt = request.cookies.getModel[VehicleTaxOrSornFormModel]
        (newKeeperDetailsOpt, vehicleDetailsOpt, vehicleSornOpt) match {
          case (Some(newKeeperDetails), Some(vehicleDetails), Some(vehicleSorn)) =>
            BadRequest(complete_and_confirm(
              CompleteAndConfirmViewModel(formWithReplacedErrors(invalidForm), vehicleDetails, newKeeperDetails, vehicleSorn), dateService)
            )
          case _ =>
            Logger.debug("Could not find expected data in cache on dispose submit - now redirecting...")
            Redirect(routes.VehicleLookup.present())
        }
      },
      validForm => {
        val newKeeperDetailsOpt = request.cookies.getModel[NewKeeperDetailsViewModel]
        val vehicleLookupOpt = request.cookies.getModel[VehicleLookupFormModel]
        val vehicleDetailsOpt = request.cookies.getModel[VehicleDetailsModel]
        val traderDetailsOpt = request.cookies.getModel[TraderDetailsModel]
        (newKeeperDetailsOpt, vehicleLookupOpt, vehicleDetailsOpt, traderDetailsOpt) match {
          case (Some(newKeeperDetails), Some(vehicleLookup), Some(vehicleDetails), Some(traderDetails)) =>
            if (config.isMicroserviceIntegrationEnabled){
            acquireAction (validForm,
                           newKeeperDetails,
                           vehicleLookup,
                           vehicleDetails,
                           traderDetails,
                           request.cookies.trackingId())}
            else {
              Future.successful {
                Logger.error("Microservice integration is disabled")
                Redirect(routes.AcquireSuccess.present()).withCookie(validForm)
              }
            }
          case (_, _, _, None) => Future.successful {
            Logger.error("Could not find either dealer details or VehicleLookupFormModel in cache on Acquire submit")
            Redirect(routes.SetUpTradeDetails.present())
          }
          case _ => Future.successful {
            Logger.debug("Could not find expected data in cache on dispose submit - now redirecting...")
            Redirect(routes.VehicleLookup.present())
          }
        }
      }<commit_msg>Complete-and-confirm now works when micro service integration is switched off. All of this ms integration code will be removed shortly<commit_after>package controllers

import com.google.inject.Inject
import models.AcquireCompletionViewModel
import models.CompleteAndConfirmFormModel
import models.CompleteAndConfirmViewModel
import models.NewKeeperDetailsViewModel
import models.VehicleLookupFormModel
import models.VehicleTaxOrSornFormModel
import models.CompleteAndConfirmFormModel.Form.{MileageId, ConsentId}
import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import play.api.data.{FormError, Form}
import play.api.mvc.{Action, AnyContent, Call, Controller, Request, Result}
import play.api.Logger
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import uk.gov.dvla.vehicles.presentation.common
import common.clientsidesession.ClientSideSessionFactory
import common.clientsidesession.CookieImplicits.{RichCookies, RichForm, RichResult}
import common.mappings.TitleType
import common.model.{VehicleDetailsModel, TraderDetailsModel}
import common.services.DateService
import common.views.helpers.FormExtensions.formBinding
import utils.helpers.Config
import views.html.acquire.complete_and_confirm
import webserviceclients.acquire.AcquireRequestDto
import webserviceclients.acquire.AcquireResponseDto
import webserviceclients.acquire.AcquireService
import webserviceclients.acquire.KeeperDetailsDto
import webserviceclients.acquire.TitleTypeDto
import webserviceclients.acquire.TraderDetailsDto

class CompleteAndConfirm @Inject()(webService: AcquireService)(implicit clientSideSessionFactory: ClientSideSessionFactory,
                                                               dateService: DateService,
                                                               config: Config) extends Controller {

  private[controllers] val form = Form(
    CompleteAndConfirmFormModel.Form.Mapping
  )

  private final val NoCookiesFoundMessage = "Failed to find new keeper details and or vehicle details and or " +
    "vehicle sorn details in cache. Now redirecting to vehicle lookup"

  def present = Action { implicit request =>
    val newKeeperDetailsOpt = request.cookies.getModel[NewKeeperDetailsViewModel]
    val vehicleDetailsOpt = request.cookies.getModel[VehicleDetailsModel]
    val vehicleSornOpt = request.cookies.getModel[VehicleTaxOrSornFormModel]
    (newKeeperDetailsOpt, vehicleDetailsOpt, vehicleSornOpt) match {
      case (Some(newKeeperDetails), Some(vehicleDetails), Some(vehicleSorn)) =>
        Ok(complete_and_confirm(CompleteAndConfirmViewModel(form.fill(), vehicleDetails, newKeeperDetails, vehicleSorn), dateService))
      case _ => redirectToVehicleLookup(NoCookiesFoundMessage)
    }
  }

  def submit = Action.async { implicit request =>
    form.bindFromRequest.fold(
      invalidForm => Future.successful {
        val newKeeperDetailsOpt = request.cookies.getModel[NewKeeperDetailsViewModel]
        val vehicleDetailsOpt = request.cookies.getModel[VehicleDetailsModel]
        val vehicleSornOpt = request.cookies.getModel[VehicleTaxOrSornFormModel]
        (newKeeperDetailsOpt, vehicleDetailsOpt, vehicleSornOpt) match {
          case (Some(newKeeperDetails), Some(vehicleDetails), Some(vehicleSorn)) =>
            BadRequest(complete_and_confirm(
              CompleteAndConfirmViewModel(formWithReplacedErrors(invalidForm), vehicleDetails, newKeeperDetails, vehicleSorn), dateService)
            )
          case _ =>
            Logger.error("Could not find expected data in cache on dispose submit - now redirecting...")
            Redirect(routes.VehicleLookup.present())
        }
      },
      validForm => {
        val newKeeperDetailsOpt = request.cookies.getModel[NewKeeperDetailsViewModel]
        val vehicleLookupOpt = request.cookies.getModel[VehicleLookupFormModel]
        val vehicleDetailsOpt = request.cookies.getModel[VehicleDetailsModel]
        val traderDetailsOpt = request.cookies.getModel[TraderDetailsModel]
        (newKeeperDetailsOpt, vehicleLookupOpt, vehicleDetailsOpt, traderDetailsOpt) match {
          case (Some(newKeeperDetails), Some(vehicleLookup), Some(vehicleDetails), Some(traderDetails)) =>
            if (config.isMicroserviceIntegrationEnabled){
            acquireAction (validForm,
                           newKeeperDetails,
                           vehicleLookup,
                           vehicleDetails,
                           traderDetails,
                           request.cookies.trackingId())}
            else {
              Future.successful {
                Logger.debug("Microservice integration is disabled")
                val transactionTimestamp = dateService.now.toDateTime

                val acquireModel = AcquireCompletionViewModel(vehicleDetails,
                  traderDetails,
                  newKeeperDetails,
                  validForm,
                  "12345",
                  transactionTimestamp)

                Redirect(routes.AcquireSuccess.present()).withCookie(acquireModel)
              }
            }
          case (_, _, _, None) => Future.successful {
            Logger.error("Could not find either dealer details or VehicleLookupFormModel in cache on Acquire submit")
            Redirect(routes.SetUpTradeDetails.present())
          }
          case _ => Future.successful {
            Logger.error("Could not find expected data in cache on dispose submit - now redirecting...")
            Redirect(routes.VehicleLookup.present())
          }
        }
      }
{'fraction_non_alphanumeric': 0.07108960640178655, 'fraction_numerical': 0.0004652461151949381, 'mean_word_length': 3.28207171314741, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5886924', 'n_tokens_mistral': 2749, 'n_tokens_neox': 2681, 'n_words': 550}