var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
/* eslint-disable class-methods-use-this */
import { withRouter, useHistory } from 'react-router-dom';
import { SwButton } from 'sw-web-shared';
import { useDispatch, useSelector } from 'react-redux';
import { useEffect, useState } from 'react';
import { Avatar, Menu, MenuItem } from '@mui/material';
import Portal from '@mui/material/Portal';
import MainDialog from './components/MainDialog';
import { setPartnerKey } from './store/sw-auth.reducer';
import { resetUIState } from './store/store';
import { isOpen, showDialog, setDisableCreateNewUser } from './store/sw-ui-reducer';
import { setLoggedIn, setUserData, currentUserState } from './store/sw-user-data.reducer';
import { setUseDev } from './services/web3/env';
var SwAuthModal = withRouter(function (_a) {
    var container = _a.container, _b = _a.rootContainer, rootContainer = _b === void 0 ? null : _b;
    var dispatch = useDispatch();
    var open = useSelector(isOpen);
    var handleClose = function () {
        dispatch(showDialog(false));
    };
    useEffect(function () {
        // increase zIndex for the custom container so that the button is under modal
        if (rootContainer) {
            rootContainer.style.zIndex = open ? '999999' : '0';
        }
    }, [open, rootContainer]);
    return (_jsx(_Fragment, { children: _jsx(MainDialog, { open: open, handleClose: handleClose, container: container }, void 0) }, void 0));
});
export var SwAuthButton = function (_a) {
    var attributes = _a.attributes, container = _a.container, setAttrCallback = _a.setAttrCallback;
    var history = useHistory();
    var dispatch = useDispatch();
    var currentUser = useSelector(currentUserState);
    var _b = useState(false), buttonHidden = _b[0], setButtonHidden = _b[1];
    var _c = useState(false), showButtonDropDown = _c[0], setShowButtonDropDown = _c[1];
    useEffect(function () {
        // Remember they are strings
        // Set attribute change callback
        setAttrCallback(function (name, oldVal, newVal) {
            if (name === 'hide-button') {
                setButtonHidden(newVal === 'true');
            }
        });
    }, []);
    useEffect(function () {
        var useButtonOptions = attributes.useButtonOptions, disableCreateNewUser = attributes.disableCreateNewUser, partnerKey = attributes.partnerKey, useDev = attributes.useDev, hideButton = attributes.hideButton;
        if (useButtonOptions) {
            console.log(useButtonOptions);
            setShowButtonDropDown(useButtonOptions === 'true');
        }
        if (hideButton) {
            setButtonHidden(hideButton === 'true');
        }
        if (useDev) {
            setUseDev(useDev === 'true');
        }
        if (partnerKey) {
            console.log('PK', partnerKey);
            dispatch(setPartnerKey(partnerKey));
            var event_1 = new CustomEvent('initSkillwalletAuth', {
                composed: true,
                cancelable: true,
                bubbles: true,
            });
            window.dispatchEvent(event_1);
        }
        if (disableCreateNewUser) {
            dispatch(setDisableCreateNewUser(disableCreateNewUser === 'true'));
        }
        var sw = JSON.parse(sessionStorage.getItem('skillWallet'));
        if (sw) {
            var currentTime = new Date().getTime();
            // 8 Hours
            var sessionLength = new Date(8 * 60 * 60 * 1000 + sw.timestamp).getTime();
            if (currentTime < sessionLength) {
                dispatch(setUserData({
                    username: sw.nickname,
                    profileImageUrl: sw.imageUrl,
                    isLoggedIn: true,
                }));
                var event_2 = new CustomEvent('onSkillwalletLogin', {
                    composed: true,
                    cancelable: true,
                    bubbles: true,
                    detail: true,
                });
                window.dispatchEvent(event_2);
            }
            else {
                window.sessionStorage.removeItem('skillWallet');
                dispatch(resetUIState);
                dispatch(setLoggedIn(false));
                var event_3 = new CustomEvent('onSkillwalletLogin', {
                    composed: true,
                    cancelable: true,
                    bubbles: true,
                    detail: false,
                });
                window.dispatchEvent(event_3);
            }
        }
    }, []);
    var _d = useState(null), anchorEl = _d[0], setAnchorEl = _d[1];
    var handleButtonClick = function () {
        if (currentUser.isLoggedIn) {
            if (!showButtonDropDown) {
                console.log('LOGOUT');
                window.sessionStorage.removeItem('skillWallet');
                dispatch(resetUIState);
                var event_4 = new CustomEvent('onSkillwalletLogin', {
                    composed: true,
                    cancelable: true,
                    bubbles: true,
                    detail: false,
                });
                window.dispatchEvent(event_4);
            }
        }
        else {
            console.log('EMPTY');
            history.push('/');
            dispatch(resetUIState);
            dispatch(showDialog(true));
        }
    };
    var handleMouseEnter = function (event) {
        console.log(showButtonDropDown);
        console.log('ENTER');
        if (anchorEl !== event.currentTarget && showButtonDropDown && currentUser.isLoggedIn) {
            console.log(event.currentTarget);
            setAnchorEl(container);
        }
    };
    var handleMenuButtonClicked = function () {
        window.sessionStorage.removeItem('skillWallet');
        dispatch(resetUIState);
        var event = new CustomEvent('onSkillwalletLogin', {
            composed: true,
            cancelable: true,
            bubbles: true,
            detail: false,
        });
        window.dispatchEvent(event);
        setAnchorEl(null);
    };
    var handleHideMenu = function () {
        setAnchorEl(null);
    };
    return (_jsx(_Fragment, { children: _jsx(Portal, __assign({ container: container }, { children: !buttonHidden && (_jsxs(_Fragment, { children: [_jsx(SwButton, { sx: {
                            height: '57px',
                            width: '180px',
                        }, mode: "dark", btnType: "medium", onClick: handleButtonClick, onMouseEnter: handleMouseEnter, label: currentUser.isLoggedIn ? currentUser.username : 'Connect Wallet', startIcon: currentUser.isLoggedIn ? _jsx(Avatar, { sx: { width: '36px', height: '36px' }, src: currentUser.profileImageUrl }, void 0) : undefined }, void 0), _jsx(Menu, __assign({ sx: {
                            '& .MuiMenu-list': {
                                padding: '0px',
                            },
                            '& .MuiPaper-root': {
                                backgroundColor: 'transparent',
                                boxShadow: 'none',
                            },
                        }, container: container, anchorEl: anchorEl, open: Boolean(anchorEl), onClose: handleHideMenu, MenuListProps: { onMouseLeave: handleHideMenu } }, { children: _jsx(MenuItem, __assign({ sx: { p: '0px' } }, { children: _jsx(SwButton, { sx: {
                                    height: '40px',
                                    width: '180px',
                                }, mode: "dark", btnType: "small", onClick: handleMenuButtonClicked, label: "Logout" }, void 0) }), void 0) }), void 0)] }, void 0)) }), void 0) }, void 0));
};
export default SwAuthModal;
