/* eslint-disable @typescript-eslint/no-unsafe-assignment */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type TypeGeneric = any;

export class SafeChainInvoker {
    target: TypeGeneric
    chain: string[]

    constructor(propChain: string, target?: TypeGeneric) {
        this.target = target
        this.chain = propChain.split('.').filter(s => s)
    }

    // @note: 此方法并无使用? 暂时先注释掉
    // setup(target: TypeGeneric) {
    //     this.target = target
    //     return this
    // }

    call(...args: TypeGeneric) {
        const target = this.target

        let prevTarget = target
        let nextTarget = target

        this.chain.every(
            propName => {
                if (nextTarget) {
                    prevTarget = nextTarget
                    // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
                    nextTarget = nextTarget[propName]
                    return true
                }
                return false
            }
        )

        if (typeof nextTarget === 'function') {
            // eslint-disable-next-line max-len
            // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-return
            return nextTarget.apply(prevTarget, args)
        }

        return undefined
    }
}
