<commit_before>/*
 * Copyright 2019 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.businessmatching

import cats.data.OptionT
import cats.implicits._
import config.AppConfig
import connectors.DataCacheConnector
import controllers.BaseController
import forms.{EmptyForm, Form2, InvalidForm, ValidForm}
import javax.inject.{Inject, Singleton}

import models.businessactivities.BusinessActivities
import models.businessmatching.{BusinessActivities => BusinessMatchingActivities, _}
import models.moneyservicebusiness.{MoneyServiceBusiness => MSBModel}
import models.responsiblepeople.{ApprovalFlags, ResponsiblePerson}
import models.supervision.Supervision
import services.StatusService
import services.businessmatching.BusinessMatchingService
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.http.cache.client.CacheMap
import uk.gov.hmrc.play.frontend.auth.AuthContext
import uk.gov.hmrc.play.frontend.auth.connectors.AuthConnector
import utils.RepeatingSection
import views.html.businessmatching._

import scala.concurrent.Future

@Singleton
class RegisterServicesController @Inject()(val authConnector: AuthConnector,
                                           val statusService: StatusService,
                                           val dataCacheConnector: DataCacheConnector,
                                           val businessMatchingService: BusinessMatchingService,
                                           val appConfig:AppConfig)() extends BaseController with RepeatingSection {

  def get(edit: Boolean = false) = Authorised.async {
    implicit authContext =>
      implicit request =>
        statusService.isPreSubmission flatMap { isPreSubmission =>
          (for {
            businessMatching <- businessMatchingService.getModel
            businessActivities <- OptionT.fromOption[Future](businessMatching.activities)
          } yield {
            val form = Form2[BusinessMatchingActivities](businessActivities)
            val (newActivities, existing) = getActivityValues(form, isPreSubmission, Some(businessActivities.businessActivities))

            Ok(register_services(form, edit, newActivities, existing, isPreSubmission, businessMatching.preAppComplete))
          }) getOrElse {
            val (newActivities, existing) = getActivityValues(EmptyForm, isPreSubmission, None)
            Ok(register_services(EmptyForm, edit, newActivities, existing, isPreSubmission, showReturnLink = false))
          }
        }
  }

  def post(edit: Boolean = false) = Authorised.async {
    implicit authContext =>
      implicit request =>
        import jto.validation.forms.Rules._
        Form2[BusinessMatchingActivities](request.body) match {
          case invalidForm: InvalidForm =>
            statusService.isPreSubmission flatMap { isPreSubmission =>
              (for {
                bm <- businessMatchingService.getModel
                businessActivities <- OptionT.fromOption[Future](bm.activities)
              } yield {
                businessActivities.businessActivities
              }).value map { activities =>
                val (newActivities, existing) = getActivityValues(
                  invalidForm,
                  isPreSubmission,
                  activities
                )
                BadRequest(
                  register_services(
                    invalidForm,
                    edit,
                    newActivities,
                    existing,
                    isPreSubmission
                  )
                )
              }
            }
          case ValidForm(_, data) =>
            formatServices(data) flatMap { action =>
              getData[ResponsiblePerson] flatMap { responsiblePeople =>

                val workFlow =
                  shouldPromptForApproval.tupled andThen
                    shouldPromptForFitAndProper.tupled

                val rps = responsiblePeople.map(rp => workFlow((rp, action._2, action._1)))

                updateResponsiblePeople(rps) map { _ =>
                  redirectTo(data.businessActivities)
                }
              }
            }
        }
  }

  private def formatServices(data: BusinessMatchingActivities)
                        (implicit ac: AuthContext, hc: HeaderCarrier) = {
    (for {
      isPreSubmission <- statusService.isPreSubmission
      businessMatching <- businessMatchingService.getModel.value
      savedModel <- updateModel(
        businessMatching,
        newModel(businessMatching.activities,
          data,
          isPreSubmission
        ),
        isMsb(data, businessMatching.activities)
      )
      _ <- maybeRemoveAccountantForAMLSRegulations(savedModel)
      _ <- clearRemovedSections(
        businessMatching.activities.getOrElse(
          BusinessMatchingActivities(
            Set()
          )
        ).businessActivities,
        savedModel.businessActivities
      )
      isRemoving <- isRemovingActivity(
        businessMatching.activities.getOrElse(
          BusinessMatchingActivities(
            Set()
          )
        ).businessActivities,<commit_msg>Refactor method name<commit_after>/*
 * Copyright 2019 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.businessmatching

import cats.data.OptionT
import cats.implicits._
import config.AppConfig
import connectors.DataCacheConnector
import controllers.BaseController
import forms.{EmptyForm, Form2, InvalidForm, ValidForm}
import javax.inject.{Inject, Singleton}

import models.businessactivities.BusinessActivities
import models.businessmatching.{BusinessActivities => BusinessMatchingActivities, _}
import models.moneyservicebusiness.{MoneyServiceBusiness => MSBModel}
import models.responsiblepeople.{ApprovalFlags, ResponsiblePerson}
import models.supervision.Supervision
import services.StatusService
import services.businessmatching.BusinessMatchingService
import uk.gov.hmrc.http.HeaderCarrier
import uk.gov.hmrc.http.cache.client.CacheMap
import uk.gov.hmrc.play.frontend.auth.AuthContext
import uk.gov.hmrc.play.frontend.auth.connectors.AuthConnector
import utils.RepeatingSection
import views.html.businessmatching._

import scala.concurrent.Future

@Singleton
class RegisterServicesController @Inject()(val authConnector: AuthConnector,
                                           val statusService: StatusService,
                                           val dataCacheConnector: DataCacheConnector,
                                           val businessMatchingService: BusinessMatchingService,
                                           val appConfig:AppConfig)() extends BaseController with RepeatingSection {

  def get(edit: Boolean = false) = Authorised.async {
    implicit authContext =>
      implicit request =>
        statusService.isPreSubmission flatMap { isPreSubmission =>
          (for {
            businessMatching <- businessMatchingService.getModel
            businessActivities <- OptionT.fromOption[Future](businessMatching.activities)
          } yield {
            val form = Form2[BusinessMatchingActivities](businessActivities)
            val (newActivities, existing) = getActivityValues(form, isPreSubmission, Some(businessActivities.businessActivities))

            Ok(register_services(form, edit, newActivities, existing, isPreSubmission, businessMatching.preAppComplete))
          }) getOrElse {
            val (newActivities, existing) = getActivityValues(EmptyForm, isPreSubmission, None)
            Ok(register_services(EmptyForm, edit, newActivities, existing, isPreSubmission, showReturnLink = false))
          }
        }
  }

  def post(edit: Boolean = false) = Authorised.async {
    implicit authContext =>
      implicit request =>
        import jto.validation.forms.Rules._
        Form2[BusinessMatchingActivities](request.body) match {
          case invalidForm: InvalidForm =>
            statusService.isPreSubmission flatMap { isPreSubmission =>
              (for {
                bm <- businessMatchingService.getModel
                businessActivities <- OptionT.fromOption[Future](bm.activities)
              } yield {
                businessActivities.businessActivities
              }).value map { activities =>
                val (newActivities, existing) = getActivityValues(
                  invalidForm,
                  isPreSubmission,
                  activities
                )
                BadRequest(
                  register_services(
                    invalidForm,
                    edit,
                    newActivities,
                    existing,
                    isPreSubmission
                  )
                )
              }
            }
          case ValidForm(_, data) =>
            formatBusinessActivities(data) flatMap { action =>
              getData[ResponsiblePerson] flatMap { responsiblePeople =>

                val workFlow =
                  shouldPromptForApproval.tupled andThen
                    shouldPromptForFitAndProper.tupled

                val rps = responsiblePeople.map(rp => workFlow((rp, action._2, action._1)))

                updateResponsiblePeople(rps) map { _ =>
                  redirectTo(data.businessActivities)
                }
              }
            }
        }
  }

  private def formatBusinessActivities(data: BusinessMatchingActivities)
                        (implicit ac: AuthContext, hc: HeaderCarrier) = {
    (for {
      isPreSubmission <- statusService.isPreSubmission
      businessMatching <- businessMatchingService.getModel.value
      savedModel <- updateModel(
        businessMatching,
        newModel(businessMatching.activities,
          data,
          isPreSubmission
        ),
        isMsb(data, businessMatching.activities)
      )
      _ <- maybeRemoveAccountantForAMLSRegulations(savedModel)
      _ <- clearRemovedSections(
        businessMatching.activities.getOrElse(
          BusinessMatchingActivities(
            Set()
          )
        ).businessActivities,
        savedModel.businessActivities
      )
      isRemoving <- isRemovingActivity(
        businessMatching.activities.getOrElse(
          BusinessMatchingActivities(
            Set()
          )
        ).businessActivities,
{'fraction_non_alphanumeric': 0.06983116768319632, 'fraction_numerical': 0.0022982409617254484, 'mean_word_length': 2.299504228638087, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '828482', 'n_tokens_mistral': 2796, 'n_tokens_neox': 2681, 'n_words': 609}