import { Component } from '../../lib/vues6/vues6.js'
import { location_service } from '../service/Location.service.js'
import { auth_api } from '../service/AuthApi.service.js'

const template = `
<div class="coreid-auth-page col-lg-6 col-md-8 col-sm-10 col-xs-12 offset-lg-3 offset-md-2 offset-sm-1 offset-xs-0 text-left">
    <div class="coreid-auth-page-inner">
        <div class="coreid-header font-weight-light">{{ app_name }}</div>
        <div class="coreid-message">
            {{ t['mfa.recover_prompt'] }}
        </div>
        <div class="form-group">
            <input
                class="form-control"
                type="text"
                :placeholder="t['mfa.recovery_code']"
                v-model="recovery_code"
                @keyup="on_key_up"
                name="recovery_code"
                :disabled="verify_success"
                ref="verify_input"
                maxlength="36"
                autofocus
            >
        </div>
        <div v-if="error_message" class="error-message">{{ error_message }}</div>
        <div v-if="other_message" class="other-message">{{ other_message }}</div>
        <small
            class="mr-3" v-if="!loading"
        ><a href="#" class="text-secondary" @click="on_do_challenge">{{ t['mfa.normal_code'] }}</a></small>
        <div class="coreid-loading-spinner" v-if="loading"><div class="inner"></div></div>
    </div>
</div>
`

export default class MFARecoveryComponent extends Component {
    static get selector() { return 'coreid-mfa-recovery-page' }
    static get template() { return template }
    static get props() { return ['app_name'] }

    constructor() {
        super()

        this.verify_success = false
        this.loading = false
        this.recovery_code = ''
        this.error_message = ''
        this.other_message = ''
        this.t = {}
    }

    async vue_on_create() {
        this.t = await T(
            'mfa.recover_prompt',
            'mfa.recovery_code',
            'mfa.normal_code',
            'mfa.recover_success',
            'mfa.invalid_code'
        )

        this.$nextTick(() => {
            this.$refs.verify_input.focus()
        })
    }

    async on_key_up($event) {
        if ( this.recovery_code.length === 36 ) {
            this.error_message = ''
            this.other_message = ''
            this.loading = true
            const result = await auth_api.attempt_mfa_recovery(this.recovery_code)
            if ( result && result.success ) {
                this.other_message = this.t['mfa.recover_success'].replace('NUM_CODES', result.remaining_codes)
                await location_service.redirect(result.next_destination, 5000)
            } else {
                this.loading = false
                this.error_message = this.t['mfa.invalid_code']
            }
        }
    }

    async on_do_challenge() {
        await location_service.redirect('/auth/mfa/challenge', 0)
    }
}
