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);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
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, swData } from './store/sw-auth.reducer';
import { resetUIState } from './store/store';
import { isOpen, showDialog, setDisableCreateNewUser, showGlobalError, startValidatingDomain, finishValidatingDomain, } from './store/sw-ui-reducer';
import { setLoggedIn, setUserData, currentUserState } from './store/sw-user-data.reducer';
import { setUseDev } from './services/web3/env';
import { validateDomain } from './services/web3/web3Service';
import { AttributeNames, checkIfAttributeHasChanged, dispatchSwEvent, parseAttributeValue } from './utils/utils';
import { OutputEventTypes } from './types/event-types';
var SwAuthModal = withRouter(function (_a) {
    var container = _a.container, _b = _a.rootContainer, rootContainer = _b === void 0 ? null : _b;
    var dispatch = useDispatch();
    var swState = useSelector(swData);
    var open = useSelector(isOpen);
    var handleClose = function (event, reason) {
        if (swState.partnerMode && reason && reason === 'backdropClick')
            return;
        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(null), anchorEl = _b[0], setAnchorEl = _b[1];
    var _c = useState(false), buttonHidden = _c[0], setButtonHidden = _c[1];
    var onSetParnersKey = function (partnerKey) {
        if (partnerKey) {
            console.log('PK', attributes.partnerKey);
            dispatch(setPartnerKey(attributes.partnerKey));
            dispatchSwEvent(OutputEventTypes.Init);
        }
        else {
            dispatch(showGlobalError('Partner key attribute is missing.'));
        }
    };
    var onUseEnv = function (useDev) { return __awaiter(void 0, void 0, void 0, function () {
        var isValid, e_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!useDev) return [3 /*break*/, 1];
                    setUseDev(attributes.useDev);
                    return [3 /*break*/, 6];
                case 1:
                    dispatch(startValidatingDomain());
                    _a.label = 2;
                case 2:
                    _a.trys.push([2, 4, 5, 6]);
                    return [4 /*yield*/, validateDomain(attributes.partnerKey)];
                case 3:
                    isValid = _a.sent();
                    if (!isValid) {
                        dispatch(showGlobalError('Invalid domain. Please add the URL throught the dashboard.'));
                    }
                    return [3 /*break*/, 6];
                case 4:
                    e_1 = _a.sent();
                    dispatch(showGlobalError('Failed to validate domain.'));
                    return [3 /*break*/, 6];
                case 5:
                    dispatch(finishValidatingDomain());
                    return [7 /*endfinally*/];
                case 6: return [2 /*return*/];
            }
        });
    }); };
    var initializeSW = function () { return __awaiter(void 0, void 0, void 0, function () {
        var sw, currentTime, sessionLength, isLoggedIn, isLoggedIn;
        return __generator(this, function (_a) {
            sw = JSON.parse(sessionStorage.getItem('skillWallet'));
            if (sw) {
                currentTime = new Date().getTime();
                sessionLength = new Date(8 * 60 * 60 * 1000 + sw.timestamp).getTime();
                if (currentTime < sessionLength) {
                    isLoggedIn = true;
                    dispatch(setUserData({
                        username: sw.nickname,
                        profileImageUrl: sw.imageUrl,
                        isLoggedIn: isLoggedIn,
                    }));
                    dispatchSwEvent(OutputEventTypes.Login, isLoggedIn);
                }
                else {
                    isLoggedIn = false;
                    window.sessionStorage.removeItem('skillWallet');
                    dispatch(resetUIState);
                    dispatch(setLoggedIn(isLoggedIn));
                    dispatchSwEvent(OutputEventTypes.Login, isLoggedIn);
                }
            }
            return [2 /*return*/];
        });
    }); };
    var handleButtonClick = function () {
        if (currentUser.isLoggedIn) {
            if (!attributes.useButtonOptions) {
                window.sessionStorage.removeItem('skillWallet');
                dispatch(resetUIState);
                dispatchSwEvent(OutputEventTypes.Login, false);
            }
        }
        else {
            history.push('/');
            dispatch(resetUIState);
            dispatch(showDialog(true));
        }
    };
    var handleMouseEnter = function (event) {
        if (anchorEl !== event.currentTarget && attributes.useButtonOptions && currentUser.isLoggedIn) {
            setAnchorEl(container);
        }
    };
    var handleMenuButtonClicked = function () {
        window.sessionStorage.removeItem('skillWallet');
        dispatch(resetUIState);
        dispatchSwEvent(OutputEventTypes.Login, false);
        setAnchorEl(null);
    };
    var handleHideMenu = function () {
        setAnchorEl(null);
    };
    useEffect(function () {
        setButtonHidden(attributes.hideButton);
        onSetParnersKey(attributes.partnerKey);
        onUseEnv(attributes.useDev);
        dispatch(setDisableCreateNewUser(attributes.disableCreateNewUser));
        setAttrCallback(function (name, prevValue, currVal) {
            var notChanged = !checkIfAttributeHasChanged(prevValue, currVal);
            if (notChanged) {
                return; // do nothing if its the same
            }
            var value = parseAttributeValue(name, currVal);
            if (name === AttributeNames.hideButton) {
                setButtonHidden(value);
            }
            else if (name === AttributeNames.disableCreateNewUser) {
                dispatch(setDisableCreateNewUser(value));
            }
        });
    }, []);
    useEffect(function () {
        initializeSW();
    }, []);
    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;
