/**
 * 守卫认证
 *
 * @class IBizAuthguard
 */
class IBizAuthguard {

    /**
     * 单列变量
     *
     * @static
     * @type {IBizAuthguard}
     * @memberof IBizAuthguard
     */
    public static iBizAuthguard: IBizAuthguard = null;

    /**
     * Creates an instance of IBizAuthguard.
     * 私有构造，拒绝通过 new 创建对象
     * 
     * @memberof IBizAuthguard
     */
    public constructor() { }

    /**
     * 获取单例
     *
     * @static
     * @returns {IBizAuthguard}
     * @memberof IBizAuthguard
     */
    public static getInstance(): IBizAuthguard {
        if (!IBizAuthguard.iBizAuthguard) {
            IBizAuthguard.iBizAuthguard = new IBizAuthguard()
        }
        return this.iBizAuthguard
    }

    /**
     * 激活守卫处理
     *
     * @param {string} url
     * @returns {Subject<boolean>}
     * @memberof IBizAuthguard
     */
    public canActivate(url: string, params: any = {}): Subject<boolean> {
        let subject: Subject<boolean> = new rxjs.Subject();
        let http: IBizHttp = IBizHttp.getInstance();
        let opt: any = { srfaction: 'loadappdata' };
        Object.assign(opt, params);
        let _params: Array<string> = [];
        Object.keys(params).forEach((name: string) => {
            if (params[name] && !Object.is(params[name], '')) {
                try {
                    JSON.parse(params[name]);
                } catch(e) {
                    _params.push(`${name}=${params[name]}`);
                }
            }
        });
        url = url.indexOf('?') !== -1 ? `${url}&${_params.join('&')}` : `${url}?${_params.join('&')}`;
        http.post(url, opt).subscribe((success: any) => {
            if (success && success.ret === 0) {
                if (success.remotetag) {
                    let win: any = window;
                    let iBizApp: IBizApp = win.getIBizApp();
                    iBizApp.setAppData(success.remotetag);
                }
            }
            subject.next(true);
        }, (error: any) => {
            subject.next(true);
        });
        return subject;
    }
}