<template>
  <div class="id-passport-validation-holder">
    <ic-passport-unique-validation
      v-if="checkUnique"
      :member-id-passport-number="icPassportNumber"
      :conditions="validationConditions"
    />
    <ic-passport-cross-sponsoring-validation
      v-if="checkCrossSponsoring"
      :sponsor-member-ibo="getSponsorDetails.member_id"
      :member-id-passport-number="icPassportNumber"
      :sponsor-id="getSponsorDetails.user_id"
    />
  </div>
</template>
<script>
import IcPassportUniqueValidation from './icPassportUniqueValidation'
import IcPassportCrossSponsoringValidation from './icPassportCrossSponsoringValidation'
import { mapGetters, mapActions, mapMutations } from 'vuex'

export default {
  name: 'IcPassportValidation',
  components: {
    IcPassportUniqueValidation,
    IcPassportCrossSponsoringValidation,
  },
  props: {
    icPassportNumber: {
      type: String,
      required: true,
    },
    icPassportNumberTypeId: {
      type: [Number, String],
      required: true,
    },
    checkUnique: {
      type: Boolean,
      default: true,
    },
    checkCrossSponsoring: {
      type: Boolean,
      default: true,
    },
    validationConditions: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    icPassportNumber: {
      handler() {
        this.activateValidation()
      },
    },
  },
  created() {
    this.activateValidation(true)
  },
  computed: {
    ...mapGetters({
      isLoading: 'isLoading',
      getOptions: 'getEnrolmentMasterDataOptionsByKey',
      getIcPassportValidationPassed: 'getIcPassportValidationPassed',
      getIcPassportNumber: 'getIcPassportNumber',
    }),
    ...mapGetters('enrolment', ['getSponsorDetails']),
  },
  methods: {
    ...mapActions(['setIcPassportValidation', 'setAutoValidationTrigger']),
    ...mapMutations({
      resetClassicCrossSponsoringVerification: 'RESET_CLASSIC_CROSS_SPONSORING_VERIFICATION',
    }),
    async activateValidation(autoTriggerStatus) {
      await this.updateIcPassportValidationData(this.icPassportNumberTypeId, this.icPassportNumber)
      if (autoTriggerStatus) {
        await this.autoValidationActivate()
      }
    },
    autoValidationActivate() {
      if (!this.checkCrossSponsoring) {
        this.resetClassicCrossSponsoringVerification()
      }
      if (this.icPassportNumber !== '') {
        this.setAutoValidationTrigger()
      }
    },
    async updateIcPassportValidationData(icPassportNumberTypeId, icPassportNumber) {
      await this.setIcPassportValidation({ ic_pass_type_id: icPassportNumberTypeId })
      await this.setIcPassportValidation({ ic_passport_number: icPassportNumber })
    },
  },
}
</script>
