// import { getCookie, setCookie } from '@modules/cookies';
import { put } from 'redux-saga/effects';
import { loggedIn, afterLoggedIn } from 'lib/redux/actions/auth-actions';
// import { getState } from '@lib/redux/store';
import { getCookie } from 'modules/cookies';
import { setHeaders } from './requests';
import { getState } from 'lib/redux/store';
// import { subscribeToMessagesChannel } from './channels/user-messages-channel';

export const isAuthenticated = (): boolean => {
	// const userState = getCookie('persist:root')?.userState ? JSON.parse(getCookie('persist:root')?.userState) : null;
	const userState = getState()['userState'];

	if (userState?.isAuthenticated) {
		if (userState?.phone_verified == 0 && window.location.pathname !== '/confirm-phone') {
			window.location.href = '/confirm-phone';
		}
		// Check whether the current time is past the access token's expiry time
		if (Date.now() < Date.parse(userState.expires_at)) {
			// dispatch(loggedIn({ data: userState }));
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
};

// export const userState = isAuthenticated() ? JSON.parse(getCookie('persist:root')?.userState) : null;

export const isAllowed = (user, permissions): boolean =>
	permissions.some(right => user.rights.includes(right));

// export const hasRole = (user, roles): boolean =>
// 	roles.some(role => user.roles.includes(role));
// 
export const hasRole = (user, role): boolean =>
	user.roles.find(ur => ur == role) ? true : false;

export const hasAnyRole = (user, roles: Array<string>): boolean =>
	user.roles.find(userRoles => roles.includes(userRoles.name)) ? true : false;

export interface userStateInterface {
	name: string,
	username: string,
	email: string,
	picture: string,
	roles: string[],
	access_token: string,
	token_type: string,
	isAuthenticated: boolean,
	expires_at: string,
	awebkey: string,
	subscriptions: object,
	unread_messages: [],
	phone_verified: boolean,
	phone: string
}

export const login = function* (userState: userStateInterface) {
	// store user data in localStorage
	// setCookie('userState', userState);

	// dispatch a success action to the store with user state
	yield put(loggedIn({ data: userState }));
	yield put(afterLoggedIn());

	
	setHeaders();

	// called in App.tsx
	// yield subscribeToMessagesChannel();
};

