import Vue from "vue";
import MFACOMP from "./index.vue";

const MFAConstructor = Vue.extend(MFACOMP);
let MFAINSTANCELIST = [];
const MFA = options => {
    const { UserId, username, EMail, callBack, cancelBack, status = 'login' } = options;
    if (!UserId) throw `UserId is requred.but ${UserId}`
    const id = `MFA${new Date().getTime()}`;
    const instance = new MFAConstructor();
    MFAINSTANCELIST.push(instance)
    instance.id = id;
    instance.vm = instance.$mount();
    if (instance.vm.visible) return;
    document.body.appendChild(instance.vm.$el);
    instance.vm.open({ UserId, username, EMail, status });
    instance.vm.$on("success", (Id) => {
        if (callBack) callBack(Id)
    });
    instance.vm.$on("closed", () => {
        if (cancelBack) cancelBack();
        document.body.removeChild(instance.vm.$el);
        instance.vm.$destroy();
        let index = MFAINSTANCELIST.findIndex(item => item.id === id);
        MFAINSTANCELIST.splice(index, 1)
    });
    return instance.vm;
}
MFA.close = () => {
    if (MFAINSTANCELIST.length <= 0) return;
    MFAINSTANCELIST.forEach(item => {
        document.body.removeChild(item.vm.$el);
        item.vm.$destroy();
    })
    MFAINSTANCELIST = [];
}
export default MFA;