/**
 * Created by vivek on 24/5/17.
 */

import { connectedRouterRedirect } from 'redux-auth-wrapper/history4/redirect';
import connectedAuthWrapper from 'redux-auth-wrapper/connectedAuthWrapper';
import { routerActions } from 'connected-react-router';
// import { routerActions } from 'react-router-redux';
// import { UserAuthWrapper } from 'redux-auth-wrapper';
import { createSelector } from 'reselect';
import { makeSelectAuthenticated } from '../v2Containers/Cap/selectors';
// import config from '../config/app';
const orginUrl = window.location.origin;
// const loginUrl = '/auth/login';

export const getIsLoggedIn = () => {
  let isLoggedIn = false;
  if (
    process.env.NODE_ENV === 'production' &&
    JSON.parse(window.localStorage.getItem('isLoggedIn'))
  ) {
    isLoggedIn = true;
  } else if (localStorage.getItem('token')) {
    isLoggedIn = true;
  }
  return isLoggedIn;
};

export const UserIsAuthenticated = connectedRouterRedirect({
  authenticatedSelector: getIsLoggedIn,
  wrapperDisplayName: 'UserIsAuthenticated',
  redirectPath: `${orginUrl}/auth/login`,
  allowRedirectBack: false,
});

const makeSelectNotAuthenticatedWithPredicate = state =>
  createSelector(
    makeSelectAuthenticated(state),
    global => !(global && global.isLoggedIn),
  );

export const UserIsNotAuthenticated = connectedRouterRedirect({
  authenticatedSelector: makeSelectNotAuthenticatedWithPredicate(),
  predicate: () => !getIsLoggedIn(),
  wrapperDisplayName: 'UserIsNotAuthenticated',
  redirectAction: routerActions.replace,
  redirectPath: (state, ownProps) => {
    // console.log('ownProps', ownProps);
    const urlParams = new URLSearchParams(ownProps.location.search);
    const redirectUrl = urlParams.get('redirect')
      ? urlParams.get('redirect')
      : '/';
    return redirectUrl;
  },
  // redirectPath: loginUrl,
  allowRedirectBack: false,
});