import EventBus, { Events, Event} from "../Events/EventBus";
import AppData from "../Common/AppData";

let instance;
const instanceKey = 'hash_392994';

class HashRouter {

    _isInit = false;
    _previousHash = '';
    constructor(key) {
        if (key !== instanceKey) {
            throw new Error('Cannot instantiate like this')
        }
    }

    init() {
        if (this._isInit) {
            return;
        }
        this._isInit = true;
        const _this = this;

        window.addEventListener('hashchange', function () {
            _this._onHashChange();
        });

        // fire on first load
        this._onHashChange();
    }

    _onHashChange() {
        
        const [route, queryString] = location.hash.split('?');
        let queryParams = null;
        if (queryString && queryString !== '') {
            queryParams = new URLSearchParams(queryString);
        }

        const currentHash = location.hash.split("?")[0].replace("#", "");
        const routes = AppData.getInstance().get('routes');
        if (!routes) {
            console.error('No routes found in AppData');
            return;
        }

        if (currentHash === '#') {
            return this._fireHashChange({
                key: 'root',
                data: routes?.root,
                queryParams
            });
        }

        for (let key in routes) {
            if (routes[key].hash === currentHash) {
                this._fireHashChange({
                    key,
                    data: routes[key],
                    queryParams
                });
                break;
            }
        }

        this._previousHash = currentHash;
    }

    _fireHashChange(payload) {

        EventBus.getInstance().triggerEvent(
            Events.HASH_CHANGE, {
                ...payload, _previousHash: this._previousHash
            }
        );
    }

    static getQueryParamFromHash(name) {
        const hash = window.location.hash;
        const queryString = hash.split('?')[1];
        if (!queryString) return null;
    
        const params = new URLSearchParams(queryString);
        return params.get(name);
    }

    static getInstance() {
        if (!instance) {
            instance = new HashRouter(instanceKey);
        }
        return instance;
    }
}
export default HashRouter;