import { getAppFromInstance } from '../global/index';
import { decodeState } from '../proxy/proxyHistory';
import { MustardName } from '../typings';
import { log } from '../utils/log';

// 监听实时地址与对应的子应用url不匹配问题
export function addEventListenerUrl (callback:()=>void) {
    window.addEventListener('popstate', callback);
    return function () {
        window.removeEventListener('popstate', callback);
    };
}

export function checkUrl (name:MustardName) {
    const app = getAppFromInstance(name); // 路由history改变前的实例
    const previousState = app.state; // history 切换前的 state
    
    const currentState = decodeState(name); // history 切换后的 state

    if(currentState && previousState) {
        if(currentState.origin !== previousState.origin) {
            log(`${name}: 域名不一致: ${previousState.origin}->${currentState.origin}`);
            return app.reload();
        }else if(currentState.index < previousState.index && previousState.flushed) {
            log(`${name}: history后退: ${previousState.origin}->${currentState.origin}`);
            return app.reload();
        }else if(currentState.index > previousState.index && currentState.flushed) {
            log(`${name}: history前进: ${previousState.origin}->${currentState.origin}`);
            return app.reload();
        }
    }
    // else{
    //     const origin = currentState?.origin || previousState?.origin;
    //     if(getURL(name, app.baseUrl)?.href !== origin) {
    //         log('checkUrl-one', name, getURL(name, app.baseUrl)?.href, origin);
    //         return app.reload();
    //     }
    // }

    app.state = decodeState(name); // 更新后自动刷新state
}