import _ from 'lodash';
import React from 'react';
import {connect} from 'react-redux';

const mapStateToProps = ({Authenticate}) => {
    return {Authenticate};
};

const withAuthorization = (authorized_roles) => (WrappedComponent, NotAuthorized = null) => {

    return connect(mapStateToProps)(class extends React.Component {

        get identity() {
            return this.props.Authenticate.authenticated;
        }

        get isSignedIn() {
            if (this.identity) {
                let exp = this.identity.exp;
                if (!exp || (exp > Date.now())) {
                    return true;
                } else {
                    // todo - redirect
                    return false;
                }
            } else {
                // todo - redirect
                return false;
            }
        }

        get isAuthorized() {
            if (!process.env.IS_PROTECTED) {
                return true;
            } else if (this.isSignedIn) {
                if (authorized_roles === '*') {
                    return true;
                } else {
                    let _roles = _.isArray(this.identity.roles)
                        ? this.identity.roles
                        : [this.identity.roles];

                    let _authorized_roles = _.isArray(authorized_roles)
                        ? authorized_roles
                        : [authorized_roles];

                    return _.intersection(_roles, _authorized_roles).length
                        ? true
                        : false;
                }
            } else {
                return false;
            }
        }

        render() {
            if (this.isAuthorized) {
                return <WrappedComponent {...this.props}/>
            } else {
                return (NotAuthorized)
                    ? <NotAuthorized {...this.props}/>
                    : null;
            }
        }

    });

};

export default withAuthorization;
