declare var GuardFactory:any;

/**
 * ParseAuthing 通过Authing实现登录逻辑,再同步至Parse.User.become身份
 */
export class ParseAuthing{
    authingGurad:any

    /**
     * Event
     * @desc
     * https://cdn.authing.co/packages/guard/doc/v5/guide/essentials/events.html
     *  */
    event:{[key:string]:Function|undefined} = {
        onLoad:undefined, // Guard初始化完成,开始渲染页面
        login:undefined, // 登陆成功回调
        loginError:undefined, // 登陆失败
        beforeLogin:undefined, // 用户触发登录前（返回<boolean ｜ Promise<boolean>>用于控制本次登录是否继续）。
        register:undefined, // 用户注册成功
        beforeRegister:undefined, // 用户触发注册前（返回<boolean ｜ Promise<boolean>>用于控制本次注册是否继续）。
    }
    constructor(options?:{
        login?:{(user:any,authenticationClient:any):void}
        loginError?:Function
        beforeLogin?:Function
        register?:Function
        beforeRegister?:Function
    }){
        this.event['login'] = options?.login
        this.event['login-error'] = options?.loginError
        this.event['beforeLogin'] = options?.beforeLogin
        this.event['register'] = options?.register
        this.event['beforeRegister'] = options?.beforeRegister
    }
    initLoginModal(){
        this.authingGurad = new GuardFactory.Guard({
            host: 'https://textbook.u2-dev.hep.com.cn', // 应用的认证地址
            appId: '6682ab96b7bd5db59d6785a0',
            redirectUri:location.origin
        })
        // 使用 start 方法挂载 Guard 组件到你指定的 DOM 节点，登录成功后返回 userInfo
        this.authingGurad.start('#authing-guard-container').then((userInfo:any) => {
            console.log('userInfo in start: ', userInfo)
        })
        // 生命周期事件绑定
        Object.keys(this.event).forEach(key=>{
            if(this.event[key]){
                this.authingGurad.on(key,this.event[key])
            }
        })
        // 定制特殊生命周期
        this.authingGurad.on("login",(user:any,authClient:any)=>{
            // 获取Authing
            let token = user?.token;
            // 执行回调
            if(typeof this.event["login"] == 'function'){
                this.event["login"](user,authClient)
            }
        })
    }
    logout(){
        this.authingGurad.logout();
    }
    async current(){
        // 获取当前用户信息
        const userInfo = await this.authingGurad.trackSession();
        console.log(userInfo);
    }
}