<commit_before>/*
 * Copyright 2018 HM Revenue & Customs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package controllers.tradingpremises

import cats.data.OptionT
import cats.implicits._
import connectors.{AmlsConnector, DataCacheConnector}
import controllers.BaseController
import forms.{EmptyForm, Form2, InvalidForm, ValidForm}
import javax.inject.{Inject, Singleton}
import models.businesscustomer.{ReviewDetails, Address => BCAddress}
import models.businessmatching.BusinessMatching
import models.tradingpremises.{Address, ConfirmAddress, TradingPremises, YourTradingPremises}
import play.api.i18n.MessagesApi
import services.{AuthEnrolmentsService, StatusService}
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.play.frontend.auth.AuthContext
import uk.gov.hmrc.play.frontend.auth.connectors.AuthConnector
import utils.{BusinessName, RepeatingSection}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

@Singleton
class ConfirmAddressController @Inject()(override val messagesApi: MessagesApi,
                                         implicit val dataCacheConnector: DataCacheConnector,
                                         val authConnector: AuthConnector,
                                         enrolments: AuthEnrolmentsService,
                                         implicit val statusService: StatusService,
                                         implicit val amlsConnector: AmlsConnector)
  extends RepeatingSection with BaseController {

  def getAddress(businessMatching: BusinessMatching): Option[BCAddress] =
    businessMatching.reviewDetails.fold[Option[BCAddress]](None)(r => Some(r.businessAddress))

  def get(index: Int) = Authorised.async {
    implicit authContext => implicit request =>
      val redirect = Redirect(routes.WhereAreTradingPremisesController.get(index))
      def ok(address: BCAddress) = Ok(views.html.tradingpremises.confirm_address(EmptyForm, address, index))

      {
        for {
          cache <- OptionT(dataCacheConnector.fetchAll)
          bm <- OptionT.fromOption[Future](cache.getEntry[BusinessMatching](BusinessMatching.key))
          address <- OptionT.fromOption[Future](getAddress(bm))
        } yield {
          getData[TradingPremises](cache, index) map {
            case x if x.yourTradingPremises.isDefined => redirect
            case _ => ok(address)
          } getOrElse ok(address)
        }
      } getOrElse redirect
  }

  def updateAddressFromBM(bname: Option[String], maybeYtp: Option[YourTradingPremises], maybeBm: Option[BusinessMatching]): Option[YourTradingPremises] = {
    val f: ReviewDetails => (String, Address) = { r =>
      {
        val address = Address(r.businessAddress.line_1,
          r.businessAddress.line_2,
          r.businessAddress.line_3,
          r.businessAddress.line_4,
          r.businessAddress.postcode.getOrElse(""))

        bname match {
          case Some(n) =>
            (n, address)
          case None =>
            (r.businessName, address)
        }
      }
    }

    (maybeBm, maybeYtp) match {
      case (Some(bm), Some(ytp)) => bm.reviewDetails.fold(maybeYtp) { r =>
        f(r) match {
          case (name, address) => Some(ytp.copy(name, address))
        }
      }
      case (Some(bm), _) => bm.reviewDetails.fold(maybeYtp) { r =>
        f(r) match {
          case (name, address) => Some(YourTradingPremises(name, address))
        }
      }
      case _ => maybeYtp
    }
  }

  def getCompanyName()(implicit hc: HeaderCarrier, ac: AuthContext) = {
    for {
      cache <- OptionT(dataCacheConnector.fetchAll)
      bm <- OptionT.fromOption[Future](cache.getEntry[BusinessMatching](BusinessMatching.key))
      rd <- OptionT.fromOption[Future](bm.reviewDetails)
      name <- BusinessName.getName(Some(rd.safeId))
    } yield name
  }

  def post(index: Int) = Authorised.async {
    implicit authContext =>
      implicit request =>
        val name: OptionT[Future, String] = for {
          amlsRegNumber <- OptionT(enrolments.amlsRegistrationNumber)
          id <- OptionT(statusService.getSafeIdFromReadStatus(amlsRegNumber))
          bName <- BusinessName.getNameFromAmls(id)
        } yield bName

        Form2[ConfirmAddress](request.body) match {<commit_msg>AMLS-4096 | Refactors - removed unnecessary method<commit_after>/*
 * Copyright 2018 HM Revenue & Customs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package controllers.tradingpremises

import cats.data.OptionT
import cats.implicits._
import connectors.{AmlsConnector, DataCacheConnector}
import controllers.BaseController
import forms.{EmptyForm, Form2, InvalidForm, ValidForm}
import javax.inject.{Inject, Singleton}
import models.businesscustomer.{ReviewDetails, Address => BCAddress}
import models.businessmatching.BusinessMatching
import models.tradingpremises.{Address, ConfirmAddress, TradingPremises, YourTradingPremises}
import play.api.i18n.MessagesApi
import services.{AuthEnrolmentsService, StatusService}
import uk.gov.hmrc.play.frontend.auth.connectors.AuthConnector
import utils.{BusinessName, RepeatingSection}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

@Singleton
class ConfirmAddressController @Inject()(override val messagesApi: MessagesApi,
                                         implicit val dataCacheConnector: DataCacheConnector,
                                         val authConnector: AuthConnector,
                                         enrolments: AuthEnrolmentsService,
                                         implicit val statusService: StatusService,
                                         implicit val amlsConnector: AmlsConnector)
  extends RepeatingSection with BaseController {

  def getAddress(businessMatching: BusinessMatching): Option[BCAddress] =
    businessMatching.reviewDetails.fold[Option[BCAddress]](None)(r => Some(r.businessAddress))

  def get(index: Int) = Authorised.async {
    implicit authContext => implicit request =>
      val redirect = Redirect(routes.WhereAreTradingPremisesController.get(index))
      def ok(address: BCAddress) = Ok(views.html.tradingpremises.confirm_address(EmptyForm, address, index))

      {
        for {
          cache <- OptionT(dataCacheConnector.fetchAll)
          bm <- OptionT.fromOption[Future](cache.getEntry[BusinessMatching](BusinessMatching.key))
          address <- OptionT.fromOption[Future](getAddress(bm))
        } yield {
          getData[TradingPremises](cache, index) map {
            case x if x.yourTradingPremises.isDefined => redirect
            case _ => ok(address)
          } getOrElse ok(address)
        }
      } getOrElse redirect
  }

  def updateAddressFromBM(bname: Option[String], maybeYtp: Option[YourTradingPremises], maybeBm: Option[BusinessMatching]): Option[YourTradingPremises] = {
    val f: ReviewDetails => (String, Address) = { r =>
      {
        val address = Address(r.businessAddress.line_1,
          r.businessAddress.line_2,
          r.businessAddress.line_3,
          r.businessAddress.line_4,
          r.businessAddress.postcode.getOrElse(""))

        bname match {
          case Some(n) =>
            (n, address)
          case None =>
            (r.businessName, address)
        }
      }
    }

    (maybeBm, maybeYtp) match {
      case (Some(bm), Some(ytp)) => bm.reviewDetails.fold(maybeYtp) { r =>
        f(r) match {
          case (name, address) => Some(ytp.copy(name, address))
        }
      }
      case (Some(bm), _) => bm.reviewDetails.fold(maybeYtp) { r =>
        f(r) match {
          case (name, address) => Some(YourTradingPremises(name, address))
        }
      }
      case _ => maybeYtp
    }
  }

  def post(index: Int) = Authorised.async {
    implicit authContext =>
      implicit request =>
        val name: OptionT[Future, String] = for {
          amlsRegNumber <- OptionT(enrolments.amlsRegistrationNumber)
          id <- OptionT(statusService.getSafeIdFromReadStatus(amlsRegNumber))
          bName <- BusinessName.getName(Some(id))
        } yield bName

        Form2[ConfirmAddress](request.body) match {
{'fraction_non_alphanumeric': 0.09477587523175919, 'fraction_numerical': 0.003926273312247791, 'mean_word_length': 2.9221556886227544, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4247656', 'n_tokens_mistral': 2570, 'n_tokens_neox': 2504, 'n_words': 591}