class TokenHandlerMsal {
    loginAuthScopes = '';
    sessionId = '';
    SPHostUrl = '';
    sessionStorageKey = "";
    userLoginName = "";
    SPLanguage = "";
    tokenExpiryDateKey = "";
    SPClientTag = "";
    SPProductNumber = "";
    myMSALObj = {};
    loginRequest = {
        scopes: [],
    };
    queryString = '';
    constructor(loginAuthScopes, SPHostUrl, sessionId, userLoginName, SPLanguage, SPClientTag, SPProductNumber, myMSALObj) {

        this.loginAuthScopes = loginAuthScopes;
        this.sessionId = sessionId;
        this.SPHostUrl = SPHostUrl;
        this.sessionStorageKey = "wzTokenValidTo." + SPHostUrl + "." + sessionId;
        this.SPLanguage = SPLanguage;
        this.SPClientTag = SPClientTag;
        this.SPProductNumber = SPProductNumber;
        this.myMSALObj = myMSALObj;

        this.userLoginName = "";
        this.tokenExpiryDateKey = "wzMsalTokenExpiryDateKey";
        this.biuldQueryString();
    }
    biuldQueryString() {
        this.queryString = "?SPHostUrl=" + this.SPHostUrl + "&userLoginName=" + this.userLoginName + "&SPLanguage=" + this.SPLanguage + "&SPClientTag=" + this.SPClientTag;
    }
        isPopupEnabled() {
            let urlpopup = "_blank";
            var newWin = window.open(urlpopup, "popup");

            if (!newWin || newWin.closed || typeof newWin.closed == 'undefined') {
                //alert("popup blocked");
                return false;
            }
            newWin.close();
            return true;
        }

        async  msalGenerateToken(forceRenewContext = false) {
            await this.myMSALObj.initialize();
            this.loginRequest.scopes = this.loginAuthScopes;

            let valToken = { IsTokenValid: false, ValidTo: null, sessionId: this.sessionId };

            if (!forceRenewContext) {
                valToken = this.validateToken();
                if (valToken.IsTokenValid) {
                    window["wizdomLoginName"] = window["wizdomLoginName"] ? window["wizdomLoginName"] : sessionStorage.getItem("wizdomLoginName");
                    return sessionStorage.getItem('WizdomAccessToken');
                }
            }

            let account = this.myMSALObj.getActiveAccount();
            const accounts = this.myMSALObj.getAllAccounts();

            if (!account && accounts.length < 1) {

                const popupResult = await this.myMSALObj.acquireTokenPopup(this.loginRequest);
                this.myMSALObj.setActiveAccount(popupResult.account);
                account = popupResult.account;
            } else {
                this.myMSALObj.setActiveAccount(account || accounts[0]);
                account = this.myMSALObj.getActiveAccount();
            }

            const tokenResponse = await this.myMSALObj.acquireTokenSilent(this.loginRequest);

            sessionStorage.setItem('WizdomAccessToken', tokenResponse.accessToken);
            sessionStorage.setItem(this.tokenExpiryDateKey, tokenResponse.expiresOn);
            sessionStorage.setItem("wizdomLoginName", tokenResponse.account.username);
            sessionStorage.setItem("wizdomDisplayName", tokenResponse.account.name);
            this.userLoginName = tokenResponse.account.username;
            window.loginName = tokenResponse.account.username;
            window.sessionStorage.setItem("wizLoginName", this.userLoginName);
            window["wizdomLoginName"] = tokenResponse.account.username;
            return tokenResponse.accessToken;
        }


        validateToken() {
            const accessToken = sessionStorage.getItem('WizdomAccessToken');
            const expiry = sessionStorage.getItem(this.tokenExpiryDateKey);

            if (!accessToken || !expiry) {
                return { IsTokenValid: false, ValidTo: null, sessionId: this.sessionId };
            }

            const expiryDate = new Date(expiry);
            const now = new Date();

            const isValid = expiryDate > now;

            return {
                IsTokenValid: isValid,
                ValidTo: expiryDate,
                sessionId: this.sessionId
            };
        }
        async  createContextToken(token) {
            try {
                var urlCreateContext = window.location.origin + '/Base/WizdomCorsProxy.aspx/CreateContextWithToken' + this.queryString;
                var responseCreateContext = await fetch(urlCreateContext, {
                    method: "POST", // *GET, POST, PUT, DELETE, etc.
                    mode: "cors", // no-cors, *cors, same-origin
                    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
                    credentials: "same-origin", // include, *same-origin, omit
                    headers: {
                        "Content-Type": "application/json; charset=utf-8",
                        "LTToken": token,
                        "SPProductNumber": this.SPProductNumber,
                        "sessionId": this.sessionId
                        // 'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    redirect: "follow", // manual, *follow, error
                    referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url

                });
                let response = await responseCreateContext.json();
                response = response.d;

                return response;
            } catch (e) {

            }
        }
    
}