import { apiMutate } from '../utilities/useAxiosMutate';
import { useEffect } from 'react';
import { ConfigService } from '../configService';
export const useOutlook = (callbackUri, onLogin) => {
    const invalidateUserSession = async () => {
        try {
            // if (ConfigService.integrationV2ApiUrl === undefined) {
            //     throw new Error('REACT_APP_INTEGRATION_V2_API_BASE is undefined')
            // }
            // const accessToken = localStorage.getItem('outlookAccessToken');
            // const response = await apiMutate(
            //     ConfigService.integrationV2ApiUrl,
            //     `OutlookIntegrationAccessToken/invalidateUserSession`,
            //     {
            //         method: "post",
            //         headers : {
            //             OutlookAccessToken: accessToken
            //         }
            //     }
            // )
        }
        catch (error) {
            console.error('Error refreshing access token:', error);
            return null;
            // }
        }
        finally {
            try {
                localStorage.removeItem('outlookAccessToken');
            }
            catch (error) {
                console.error('Error removing accessToken:', error);
            }
            try {
                localStorage.removeItem('outlookRefreshToken');
            }
            catch (error) {
                console.error('Error removing refreshToken:', error);
            }
            try {
                localStorage.removeItem('outlookExpiresAt');
            }
            catch (error) {
                console.error('Error removing expiresAt:', error);
            }
        }
    };
    const getAccessToken = async () => {
        let accessToken = localStorage.getItem('outlookAccessToken');
        if (!accessToken) {
            throw (new Error("No access token found"));
        }
        const expiresAt = localStorage.getItem('outlookExpiresAt');
        if (expiresAt && !isBeforeCurrentTime(expiresAt)) {
            return accessToken;
        }
        const refreshToken = localStorage.getItem('outlookRefreshToken');
        if (!refreshToken) {
            throw (new Error("No refresh token found"));
        }
        try {
            if (ConfigService.integrationV2ApiUrl === undefined) {
                throw new Error('REACT_APP_INTEGRATION_V2_API_BASE is undefined');
            }
            const response = await apiMutate(ConfigService.integrationV2ApiUrl, `OutlookIntegrationAccessToken/getAccessToken`, {
                method: "post",
                data: {
                    option: "refresh_token",
                    value: refreshToken,
                    redirectUri: ConfigService.config.UNITY_URL + "/aad_redirect"
                }
            });
            const data = response.data;
            if (data.accessToken != null && data.refreshToken != null && data.expiresIn != null) {
                localStorage.setItem('outlookAccessToken', data.accessToken);
                localStorage.setItem('outlookRefreshToken', data.refreshToken);
                localStorage.setItem('outlookExpiresAt', addSecondsToCurrentTimeUnix(data.expiresIn));
                return data.accessToken;
            }
            else {
                throw (new Error("Error: unable to get access token"));
            }
        }
        catch (error) {
            console.error('Error refreshing access token:', error);
            return null;
        }
    };
    const login = () => {
        var _a;
        const baseUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
        let clientId;
        // if the process is defined (using the vite-plugin-environment) use the env variable
        if (process !== undefined)
            // eslint-disable-next-line custom-rules/no-process-env
            clientId = process.env.REACT_APP_MSAL_API_CLIENT_ID;
        // otherwise use the config service and strip the scope part so its just the guid
        else
            clientId = (_a = ConfigService.config.MSAL_API_ACCESS_SCOPE) === null || _a === void 0 ? void 0 : _a.split('/')[0];
        const responseType = 'code';
        const redirectUri = `${ConfigService.config.UNITY_URL}/aad_redirect`;
        const responseMode = 'query';
        const scope = [
            'https://graph.microsoft.com/Calendars.ReadWrite',
            'https://graph.microsoft.com/Calendars.ReadWrite.Shared',
            'https://graph.microsoft.com/OnlineMeetingTranscript.Read.All',
            'https://graph.microsoft.com/OnlineMeetings.Read',
        ].join('%20'); // Join scopes with URL-encoded space
        const authUrl = `${baseUrl}?client_id=${clientId}&response_type=${responseType}&redirect_uri=${redirectUri}&response_mode=${responseMode}&scope=${scope}&state=${callbackUri}`;
        openLoginPopup(authUrl);
        // window.location.href = authUrl;
    };
    function openLoginPopup(url) {
        var width = 600;
        var height = 600;
        var left = (screen.width - width) / 2;
        var top = (screen.height - height) / 2;
        var features = `width=${width},height=${height},top=${top},left=${left},status=no,toolbar=no,menubar=no,location=no`;
        var popup = window.open(url, 'LoginPopup', features);
        return popup;
    }
    function addSecondsToCurrentTimeUnix(seconds) {
        var now = new Date();
        now.setSeconds(now.getSeconds() + seconds);
        return now.getTime();
    }
    function isBeforeCurrentTime(unixTime) {
        var now = new Date().getTime();
        return unixTime < now;
    }
    const isUserSignedIn = () => {
        const accessToken = localStorage.getItem('outlookAccessToken');
        const refreshToken = localStorage.getItem('outlookRefreshToken');
        const expiresAt = localStorage.getItem('outlookExpiresAt');
        if (accessToken && refreshToken && expiresAt && !isBeforeCurrentTime(expiresAt)) {
            return true;
        }
        else {
            return false;
        }
    };
    useEffect(() => {
        const handleStorageChange = (event) => {
            if (event.key === 'outlookAccessToken') {
                onLogin();
            }
        };
        window.addEventListener('storage', handleStorageChange);
        // Clean up the event listener
        return () => {
            window.removeEventListener('storage', handleStorageChange);
        };
    }, []);
    return { getAccessToken, invalidateUserSession, login, isUserSignedIn };
};
//# sourceMappingURL=useOutlook.js.map