<%@ Page Language="C#" Title="" MasterPageFile="~/Views/Shared/Server.Master" Inherits="System.Web.Mvc.ViewPage<AdministratorConsole.Models.ServerController.OAuthSettingsViewModel>" %>

<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
    <div id="content-wrap">
        <% Html.RenderPartial("Navigation/_SideNavigation", Model.MenuNavigationModel); %>
        <div id="content" class="oauth-settings-page">
            
            <% Html.RenderPartial("Partials/SystemSettingsNavigationPartial", "oauth"); %>

            <p>OAuth is a mechanism for providing an application like Clarity access to data that resides in a different cloud-based system.</p>
            <p>To enable access, click 'Add or Update Credentials' below, and follow the prompts to enable Clarity to access data in the other system.</p>
            <p>You may specify more than one set of credentials for each service here, then choose which is used by each project.</p>
            <br />
            <% foreach (OauthIdentifier oauthIdentifier in Model.OauthIdentifiers)
                { %>
                <h2><%= oauthIdentifier.DisplayName %></h2>
                <div id="error-container_<%= oauthIdentifier.ExternalId %>" class="error-container bottom-padded validation-summary-error" style="display: none;"></div>
                <% 
                    OauthToken defaultToken = Model.DefaultOauthToken(oauthIdentifier.Id);
                    IList<OauthToken> nonDefaultTokens = Model.NoneDefaultOauthToken(oauthIdentifier.Id);
                %>
                <div>
                    <div id="default-token-layout-container_<%= oauthIdentifier.ExternalId %>" class="table-row" <% if (defaultToken == null)
                        { %>style="display: none;"<% } %>>
                        <div class="table-cell bottom-padded top-aligned" style="width: 95px;"><b>Default:</b></div>
                        <div id="default-token-container_<%= oauthIdentifier.ExternalId %>" class="table-cell bottom-padded top-aligned" style="min-width: 400px;">
                            <% if (defaultToken != null)
                                { %><div id="token-layout-container_<%= defaultToken.Id %>"><% Html.RenderPartial("Partials/OAuthToken", new AdministratorConsole.Models.ServerController.Partials.OAuthTokenViewModel(Model.GetAssignedProjects(defaultToken.Id), oauthIdentifier, defaultToken, (nonDefaultTokens.Count == 0))); %></div><% } %>
                        </div>
                        <% if (oauthIdentifier.Name.Equals("BIM360", StringComparison.OrdinalIgnoreCase)){ %>
                        <div class="table-cell" style="padding-left:4rem;">
                            <div class="bottom-padded"><a href="javascript:openCreateSSAWindow('<%= oauthIdentifier.ExternalId %>')">Request a Secure Service Account</a></div>
                            <div><input type="button" value="Find Out More" class="button" onclick="showSSAHelp()" /></div>
                        </div>
                        <% } %>  
                    </div>
                    <div id="secondary-tokens-layout-container_<%= oauthIdentifier.ExternalId %>" class="table-row" <% if ((nonDefaultTokens == null) || (nonDefaultTokens.Count == 0))
                        { %>style="display: none;"<% } %>>
                        <div class="table-cell bottom-padded top-aligned" style="width: 95px;"><b>Secondary:</b></div>
                        <div id="secondary-tokens-container_<%= oauthIdentifier.ExternalId %>" class="table-cell bottom-padded top-aligned">
                            <% if ((nonDefaultTokens != null) && (nonDefaultTokens.Count > 0))
                                { %>
                                <% foreach (OauthToken nonDefaultToken in nonDefaultTokens)
                                    { %>
                                    <div id="token-layout-container_<%= nonDefaultToken.Id %>" class="bottom-padded"><% Html.RenderPartial("Partials/OAuthToken", new AdministratorConsole.Models.ServerController.Partials.OAuthTokenViewModel(Model.GetAssignedProjects(nonDefaultToken.Id), oauthIdentifier, nonDefaultToken, true)); %></div>
                                <% } %>
                            <% } %>
                        </div>
                    </div>
                </div>
                <% if (oauthIdentifier.Name.Equals("BIM360", StringComparison.OrdinalIgnoreCase)){ %>
                   <div class="d-flex gap-5">
                       <a href="javascript:load<%= oauthIdentifier.VariableName %>Authentication('<%= oauthIdentifier.GetAuthenticateURL() %>')">Add or Update Credentials</a>
                           <% if (defaultToken == null){ %>
                                <div>
                                    <div class="bottom-padded">
                                        <a href="javascript:openCreateSSAWindow('<%= oauthIdentifier.ExternalId %>')">Request a Secure Service Account</a>
                                    </div>
                                    <div><input type="button" value="Find Out More" class="button" onclick="showSSAHelp()" /></div>
                                </div>
                            <% } %>  
                   </div>
                <% } else if (oauthIdentifier.Name.Equals("Microsoft Office 365", StringComparison.OrdinalIgnoreCase)){ %>
                    <div><a href="javascript:load<%= oauthIdentifier.VariableName %>Authentication('<%= oauthIdentifier.GetAuthenticateURL() %>', '<%= oauthIdentifier.ExternalId %>')">Add or Update Credentials</a></div>
                <% } else if (oauthIdentifier.OauthType.Equals("ThreeLegged", StringComparison.OrdinalIgnoreCase)) { %>
                    <div><a href="javascript:load<%= oauthIdentifier.VariableName %>Authentication('<%= oauthIdentifier.GetAuthenticateURL() %>')">Add or Update Credentials</a></div>
                <% } else if (oauthIdentifier.OauthType.Equals("TwoLegged", StringComparison.OrdinalIgnoreCase)) { %>
                    <div><a href="javascript:openTwoLeggedOAuthWindow('<%= oauthIdentifier.ExternalId %>')">Add or Update Credentials</a></div>
                <% }else if (oauthIdentifier.OauthType.Equals("Token", StringComparison.OrdinalIgnoreCase)) { %>
                    <div><a href="javascript:openTokenOAuthWindow('<%= oauthIdentifier.ExternalId %>')">Add or Update Credentials</a></div>
                <% } %>               
                <br />
                <br />
            <% } %>
            <% using (Html.BeginForm("OAuthSettings", "Server")) { %>
                <table class="standard-list" cellspacing="0" cellpadding="0">
                    <tr>
                        <td style="padding-right:5px;" class="label">Notification Email(s):</td>
                        <td style="padding-right:5px;"><%= Html.TextBox("NotificationEmails", Model.NotificationEmails, new { @class = "standard-textbox" })%></td>
                        <td style="padding-right:15px;"><div style="position:relative" onmouseover="MakeDivVisible('ToolTip_notification');" onmouseout="MakeDivInvisible('ToolTip_notification');"><img src="<%= Request.ApplicationPath.TrimEnd(new char[] { '/' }) %>/Images/Icons/help.png" border="0" /><div id="ToolTip_notification" class="tool-tip tool-tip-over" style="width:250px;">A comma-delimited list of email addresses to notify if Clarity detects that the oAuth Token has gone bad.</div></div></td>
                        <td><input type="submit" value="Update" class="button" /></td>
                    </tr>
                </table>
            <% } %>
            <script type="text/javascript">
                var randAuthURL = "<%= Model.GetRandAuthURL() %>";

                function showSSAHelp() {
                    window.open("<%= WebHelpHelper.WebHelpStandardURL + "index.htm#t=Admin_%26_Coordinators_Guide%2FBIM360_Collaboration_for_Revit%2FWhat_is_SSA_.htm" %>", "_blank");
                }

                if (location.protocol.toLowerCase() === "https:") {
                    var httpLength = "http:".length;

                    if (randAuthURL.substring(0, httpLength).toLowerCase() == "http:") randAuthURL = "https:" + randAuthURL.substring(httpLength);
                }

                function openThreeLeggedOAuthWindow(urlLocation) {
                    $(".error-container").hide();
                    $(".error-container").empty();

                    window.open(randAuthURL + urlLocation, "_blank");
                }

                function loadMicrosoftOffice365Authentication(urlLocation, oauthIdentiferId) {
                    $.ajax({
                        type: 'GET',
                        url: '<%= Url.Action("GetOffice365Tenant", "Server") %>',
                        data: {
                            externalId: oauthIdentiferId
                        },
                        cache: false,
                        success: function (response) {
                            $("#modal-overlay").html(response);
                        },
                        complete: function () {
                            showModelDialog();
                        }
                    });
                }

                function openAdditionalParameter(oauthIdentiferId) {
                    $.ajax({
                        type: 'GET',
                        url: '<%= Url.Action("GetOffice365AdditionalParameter", "Server") %>',
                        data: {
                            oauthIdentiferId: oauthIdentiferId
                        },
                        cache: false,
                        success: function (response) {
                            $("#modal-overlay").html(response);
                        },
                        complete: function () {
                            showModelDialog();
                        }
                    });
                }

                function openTwoLeggedOAuthWindow(oauthIdentiferId) {
                    $.ajax({
                        type: 'GET',
                        url: '<%= Url.Action("GetCreateTwoLeggedToken", "Server") %>',
                        data: {
                            oauthIdentiferId: oauthIdentiferId
                        },
                        cache: false,
                        success: function (response) {
                            $("#modal-overlay").html(response);
                        },
                        complete: function () {
                            showModelDialog();
                        }
                    });
                }

                function openTokenOAuthWindow(oauthIdentiferId) {
                    $.ajax({
                        type: 'GET',
                        url: '<%= Url.Action("GetCreateSingleEntryToken", "Server") %>',
                        data: {
                            oauthIdentiferId: oauthIdentiferId
                        },
                        cache: false,
                        success: function (response) {
                            $("#modal-overlay").html(response);
                        },
                        complete: function () {
                            showModelDialog();
                        }
                    });
                }

                function openCreateSSAWindow() {
                    $.ajax({
                        type: 'GET',
                        url: '<%= Url.Action("AddSecureServiceAccountToken", "Server") %>',
                         cache: false,
                         success: function (response) {
                             $("#modal-overlay").html(response);
                         },
                         complete: function () {
                             showModelDialog();
                         }
                     });
                }

                function renameToken(tokenId) {
                    $.ajax({
                        type: 'GET',
                        url: '<%= Url.Action("GetRenameToken", "Server") %>',
                        data: {
                            tokenId: tokenId
                        },
                        cache: false,
                        success: function (response) {
                            $("#modal-overlay").html(response);
                        },
                        complete: function () {
                            showModelDialog();
                        }
                    });
                }

                function showBIM360LiveCheck(tokenId) {
                    $.ajax({
                        type: 'GET',
                        url: '<%= Url.Action("BIM360LiveCheck", "Server") %>',
                        data: {
                            tokenId: tokenId
                        },
                        cache: false,
                        success: function (response) {
                            $("#modal-overlay").html(response);
                        },
                        complete: function () {
                            showModelDialog();
                        }
                    });
                }

                function showSsaEmail(email) {
                    $.ajax({
                        type: 'GET',
                        url: '<%= Url.Action("ShowSSAEmail", "Server") %>',
                        data: {
                            email: email
                        },
                        cache: false,
                        success: function (response) {
                            $("#modal-overlay").html(response);
                        },
                        complete: function () {
                            showModelDialog();
                        }
                    });
                }

                function confirmDeleteToken(tokenId) {
                    $.ajax({
                        type: 'GET',
                        url: '<%= Url.Action("DeleteOAuthTokenConfirm", "Server") %>',
                        data: {
                            tokenId: tokenId
                        },
                        cache: false,
                        success: function (response) {
                            $("#modal-overlay").html(response);
                        },
                        complete: function () {
                            showModelDialog();
                        }
                    });
                }

                function viewAssignedToProjects(oauthTokenId) {
                    if ($("#oauth-projects-container_" + oauthTokenId).is(":visible")) $("#oauth-projects-container_" + oauthTokenId).hide();
                    else $("#oauth-projects-container_" + oauthTokenId).show();
                }

                function oauthIdentifierCheck(oathIdentifierCheckURL, authenticateTokenURL, authenticateUserURL, oathIdentifierId, oathIdentifierName) {
                    $.ajax({
                        type: 'POST',
                        url: randAuthURL + oathIdentifierCheckURL,
                        cache: false,
                        success: function (authToken) {
                            console.info(`${randAuthURL}${oathIdentifierCheckURL} - token:${authToken}`)
                            if (authToken.length > 0) {
                                console.log("Response retrieved from " + oathIdentifierName + ": " + randAuthURL + oathIdentifierCheckURL);
                                var tenantId = sessionStorage.getItem(oathIdentifierName);
                                var url = `${randAuthURL}${authenticateTokenURL}`;
                                if (tenantId != null) {
                                    console.info(`tenantId from sessionStorage key:${oathIdentifierName}, value:${tenantId}`);
                                    url = url + `?tenatId=${tenantId}`;
                                }

                                $.ajax({
                                    type: 'POST',
                                    url: url,
                                    cache: false,
                                    data: {
                                        id: authToken
                                    },
                                    success: function (response) {
                                        if (response.length > 0) {
                                            console.log("An authentication token received from " + oathIdentifierName + ": " + randAuthURL + authenticateTokenURL);

                                            var responseJSON = JSON.parse(response);
                                            $.ajax({
                                                type: 'POST',
                                                url: randAuthURL + authenticateUserURL,
                                                cache: false,
                                                data: {
                                                    "accessToken": responseJSON.access_token,
                                                    "additional": responseJSON["additional"]
                                                },
                                                success: function (userResponse) {
                                                    console.log("Response for the authenticated user received from " + oathIdentifierName + ": " + randAuthURL + authenticateTokenURL);
                                                    var additional = sessionStorage.getItem(oathIdentifierName);
                                                    if (additional == null) {
                                                        additional = responseJSON["additional"];
                                                        console.info(`Use additional from reponse ${additional}`);
                                                    } else {
                                                        console.info(`Get additional from sessionStorage key:${oathIdentifierName} value:${additional}`);
                                                    }

                                                    $.ajax({
                                                        type: 'POST',
                                                        url: '<%= Url.Action("UpdateOAuthSettings", "Server") %>',
                                                        cache: false,
                                                        data: {
                                                            settingId: oathIdentifierId,
                                                            access_token: responseJSON.access_token,
                                                            refresh_token: responseJSON.refresh_token,
                                                            additional: additional,
                                                            expires_in: responseJSON.expires_in,
                                                            authenticatedBy: userResponse
                                                        },
                                                        success: function (tokenResponse) {
                                                            if (tokenResponse.trim().length > 0) {
                                                                var tokenId = parseInt(tokenResponse);

                                                                $.ajax({
                                                                    type: 'GET',
                                                                    url: '<%= Url.Action("GetOAuthToken", "Server") %>',
                                                                    cache: false,
                                                                    data: {
                                                                        oauthIdentiferId: oathIdentifierId,
                                                                        tokenId: tokenId
                                                                    },
                                                                    success: function (tokenLayout) {
                                                                        if ((tokenLayout != null) && (tokenLayout.length)) {
                                                                            console.log("Token layout received");

                                                                            if ($("#token-layout-container_" + tokenId).length) {
                                                                                console.log("Token layout already exists: " + tokenId);

                                                                                $("#token-layout-container_" + tokenId).html(tokenLayout);
                                                                            }
                                                                            else {
                                                                                console.log("Token layout does not exist: " + tokenId);

                                                                                if ($("#default-token-layout-container_" + oathIdentifierId).is(":hidden")) {
                                                                                    console.log("Default token layout is not visible for " + oathIdentifierId);

                                                                                    $("#default-token-container_" + oathIdentifierId).html(tokenLayout);

                                                                                    $("#default-token-layout-container_" + oathIdentifierId).show();
                                                                                }
                                                                                else {
                                                                                    console.log("Default token layout is visible: " + oathIdentifierId);

                                                                                    $("#secondary-tokens-container_" + oathIdentifierId).append("<div id=\"token-layout-container_" + tokenId + "\">" + tokenLayout + "</div>");

                                                                                    $("#secondary-tokens-layout-container_" + oathIdentifierId).show();

                                                                                    $("#default-token-container_" + oathIdentifierId).find(".delete-container").hide();
                                                                                }
                                                                            }
                                                                        }
                                                                        else {
                                                                            $("#error-container_" + oathIdentifierId).html("Unable to retrieve OAuth token");
                                                                            $("#error-container_" + oathIdentifierId).show();
                                                                        }
                                                                    }
                                                                });
                                                            }
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        }
                    });
                }

                <% foreach (OauthIdentifier oauthIdentifier in Model.OauthIdentifiers) { %>
                    <% if (oauthIdentifier.OauthType.Equals("ThreeLegged", StringComparison.OrdinalIgnoreCase)) { %>
                        var <%= oauthIdentifier.VariableName %>PollingStarted = new Date();
                        <% if (!oauthIdentifier.Name.Equals("Microsoft Office 365", StringComparison.InvariantCultureIgnoreCase)) { %>              
                            function load<%= oauthIdentifier.VariableName %>Authentication(urlLocation) {
                                <%= oauthIdentifier.VariableName %>PollingStarted = new Date();

                                openThreeLeggedOAuthWindow(urlLocation);
                            }
                        <% } %>
                        setInterval(function () {
                            let diff = (new Date()) - <%= oauthIdentifier.VariableName %>PollingStarted; 

                            let minutes = Math.floor((diff / 1000) / 60);

                            if (minutes < 2) oauthIdentifierCheck('<%= oauthIdentifier.GetCheckURL() %>', '<%= oauthIdentifier.GetAuthenticateToken() %>', '<%= oauthIdentifier.GetAuthenticatedUser() %>', '<%= oauthIdentifier.ExternalId %>', '<%= oauthIdentifier.VariableName %>');
                        }, 1000);
                    <% } %>
                <% } %>
            </script>
        </div>
    </div>
</asp:Content>
