 <%--
--%>

<%@ page import="org.jivesoftware.openfire.session.IncomingServerSession,
                 org.jivesoftware.util.JiveGlobals,
                 org.jivesoftware.util.StringUtils,
                 java.util.Calendar,
                 java.util.Date"%>
 <%@ page import="java.net.*" %>
 <%@ page import="java.nio.charset.StandardCharsets" %>

 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

 <%--
   - This page is meant to be included in other pages. It assumes 4 variables:
   -     * 'host', the name of the remote server
   -     * 'inSession', an  IncomingServerSession object
   -     * 'outSession', an OutgoingServerSession object
   -     * 'count', an int representing the row number we're on.
 --%>

<% // Show the secured icon only if ALL sessions are secure
    boolean isEncrypted = true;
    Set<String> tlsProtocolNames = new HashSet<>();
    Set<String> cipherSuiteNames = new HashSet<>();
    // Check if all incoming sessions are secured
    for (org.jivesoftware.openfire.session.IncomingServerSession inSession : inSessions) {
        if (!inSession.isEncrypted()) {
            isEncrypted = false;
            break;
        }
        tlsProtocolNames.add(inSession.getTLSProtocolName());
        cipherSuiteNames.add(inSession.getCipherSuiteName());
    }
    // Check if outgoing session is secured (only if incoming sessions are secured)
    if (isEncrypted) {
        for (org.jivesoftware.openfire.session.OutgoingServerSession outSession : outSessions) {
            if (!outSession.isEncrypted()) {
                isEncrypted = false;
                break;
            }
            tlsProtocolNames.add(outSession.getTLSProtocolName());
            cipherSuiteNames.add(outSession.getCipherSuiteName());
        }
    }
    String isEncryptedAltText = isEncrypted ? String.join(", ", tlsProtocolNames) + " - " + String.join(", ", cipherSuiteNames): "";
%>
<tr>
    <td style="width: 1%; white-space: nowrap"><%= count %></td>
    <td style="width: 47%; white-space: nowrap">
        <table>
            <tr>
            <td style="width: 1%; padding-right: 0.5em" ><img src="getFavicon?host=<%=URLEncoder.encode(host, StandardCharsets.UTF_8)%>" width="16" height="16" alt=""></td>
            <td><a href="server-session-details.jsp?hostname=<%= URLEncoder.encode(host, StandardCharsets.UTF_8) %>" title="<fmt:message key='session.row.click' />"><%= StringUtils.escapeHTMLTags(host) %></a></td>
            </tr>
        </table>
    </td>
    <%  if (isEncrypted) { %>
    <td style="width: 1%">
        <img src="images/lock.gif" alt="<%=isEncryptedAltText%>">
    </td>
     <% } else { %>
    <td style="width: 1%"><img src="images/blank.gif" width="1" height="1" alt=""></td>
     <% } %>
    <% if (!inSessions.isEmpty() && outSessions.isEmpty()) { %>
        <td style="width: 1%">
            <img src="images/incoming_32x16.gif" width="32" height="16" title="<fmt:message key='server.session.connection.incoming' />" alt="<fmt:message key='server.session.connection.incoming' />">
        </td>
        <td><fmt:message key="server.session.connection.incoming" /></td>
    <% } else if (inSessions.isEmpty() && !outSessions.isEmpty()) { %>
        <td style="width: 1%">
            <img src="images/outgoing_32x16.gif" width="32" height="16" title="<fmt:message key='server.session.connection.outgoing' />" alt="<fmt:message key='server.session.connection.outgoing' />">
        </td>
        <td><fmt:message key="server.session.connection.outgoing" /></td>
    <% } else { %>
        <td style="width: 1%">
            <img src="images/both_32x16.gif" width="32" height="16" title="<fmt:message key='server.session.connection.both' />" alt="<fmt:message key='server.session.connection.both' />">
        </td>
        <td><fmt:message key="server.session.connection.both" /></td>
    <% } %>

    <%
        final boolean hasInIPv4 = inSessions.stream().anyMatch(s-> {
            try {
                return InetAddress.getByName(s.getHostAddress()) instanceof Inet4Address;
            } catch (UnknownHostException e) {
                return false;
            }
        });
        final boolean hasOutIPv4 = outSessions.stream().anyMatch(s-> {
            try {
                return InetAddress.getByName(s.getHostAddress()) instanceof Inet4Address;
            } catch (UnknownHostException e) {
                return false;
            }
        });

        final boolean hasInIPv6 = inSessions.stream().anyMatch(s-> {
            try {
                return InetAddress.getByName(s.getHostAddress()) instanceof Inet6Address;
            } catch (UnknownHostException e) {
                return false;
            }
        });
        final boolean hasOutIPv6 = outSessions.stream().anyMatch(s-> {
            try {
                return InetAddress.getByName(s.getHostAddress()) instanceof Inet6Address;
            } catch (UnknownHostException e) {
                return false;
            }
        });
        final boolean hasIPv4 = hasInIPv4 || hasOutIPv4;
        final boolean hasIPv6 = hasInIPv6 || hasOutIPv6;
    %>
    <% if (hasIPv4 && hasIPv6) { %>
    <td><fmt:message key="server.session.connection.both" /></td>
    <% } else if (hasIPv4) { %>
    <td><fmt:message key="global.ipv4" /></td>
    <% } else if (hasIPv6) { %>
    <td><fmt:message key="global.ipv6" /></td>
    <% } else { %>
    <td></td>
    <% } %>
    <%
        Date creationDate = null;
        Date lastActiveDate = null;
        for (IncomingServerSession inSession : inSessions) {
        	Date tmpCreationDate=inSession.getCreationDate();
            if (creationDate == null || (tmpCreationDate!=null && creationDate.after(tmpCreationDate))) {
                // Use the creation date of the oldest incoming session
                creationDate = tmpCreationDate;
            }
            Date tmpLastActiveDate=inSession.getLastActiveDate();
            if (lastActiveDate == null || (tmpLastActiveDate!=null && lastActiveDate.before(tmpLastActiveDate))){
                // Use the last active date of the newest incoming session
                lastActiveDate = tmpLastActiveDate;
            }
        }
        for (OutgoingServerSession outSession : outSessions) {
        	Date tmpCreationDate=outSession.getCreationDate();
            if (creationDate == null || (tmpCreationDate!=null && creationDate.after(tmpCreationDate))) {
                // Use the creation date of the oldest outgoing session
                creationDate = tmpCreationDate;
            }
            Date tmpLastActiveDate=outSession.getLastActiveDate();
            if (lastActiveDate == null || (tmpLastActiveDate!=null && lastActiveDate.before(tmpLastActiveDate))) {
                // Use the last active date of the newest outgoing session
                lastActiveDate = tmpLastActiveDate;
            }
        }

        Calendar nowCal = Calendar.getInstance();

        String creationDateString = "";
        if (creationDate!=null)
        {
            Calendar creationCal = Calendar.getInstance();
            creationCal.setTime(creationDate);
            boolean sameCreationDay = nowCal.get(Calendar.DAY_OF_YEAR) == creationCal.get(Calendar.DAY_OF_YEAR) && nowCal.get(Calendar.YEAR) == creationCal.get(Calendar.YEAR);
            creationDateString = sameCreationDay ? JiveGlobals.formatTime(creationDate) : JiveGlobals.formatDateTime(creationDate);
        }

        String lastActivityString = "";
        if(lastActiveDate!=null){
            Calendar lastActiveCal = Calendar.getInstance();
            lastActiveCal.setTime(lastActiveDate);
            boolean sameActiveDay = nowCal.get(Calendar.DAY_OF_YEAR) == lastActiveCal.get(Calendar.DAY_OF_YEAR) && nowCal.get(Calendar.YEAR) == lastActiveCal.get(Calendar.YEAR);
            lastActivityString = sameActiveDay ? JiveGlobals.formatTime(lastActiveDate) : JiveGlobals.formatDateTime(lastActiveDate);
        }


    %>

    <td style="text-align: center;" nowrap>
        <%= creationDateString %>
    </td>
    <td style="text-align: center;" nowrap>
        <%= lastActivityString %>
    </td>

    <td style="width: 1%; white-space: nowrap; text-align: center;">
        <a href="server-session-summary.jsp?hostname=<%= URLEncoder.encode(host, StandardCharsets.UTF_8) %>&close=true&csrf=${csrf}"
         title="<fmt:message key="session.row.click_kill_session" />"
         onclick="return confirm('<fmt:message key="session.row.confirm_close" />');"
         ><img src="images/delete-16x16.gif" alt="Delete"></a>
    </td>
</tr>
