import { isPlatformBrowser } from '@angular/common';
import { FactoryProvider, InjectionToken, PLATFORM_ID } from '@angular/core';

export const WINDOW = new InjectionToken<Window & typeof globalThis>('window');

export const windowProvider: FactoryProvider = {
    provide: WINDOW,
    useFactory: resolveWindow,
    deps: [PLATFORM_ID],
};

function resolveWindow(platformId) {
    if (isPlatformBrowser(platformId)) {
        return window;
    }

    // window stub for server rendering
    return {
        open: () => {
            /* */
        },
        location: {
            href: '',
        },
        navigator: {
            geolocation: { getCurrentPosition: () => Promise.reject() },
        },
        scrollTo: () => {
            /* */
        },
    };
}
