<%-- 
  Copyright 2003 Sun Microsystems, Inc. All rights reserved. 
  Use is subject to license terms.
 --%> 

<%@ page import="java.util.Enumeration" %>
<%@ page import="java.util.*" %>
<%@ page import="com.iplanet.sso.SSOTokenManager" %>
<%@ page import="com.iplanet.sso.SSOToken" %>
<%@ page import="com.iplanet.am.sdk.AMStoreConnection" %>
<%@ page import="com.iplanet.am.sdk.AMException" %>
<%@ page import="com.iplanet.sso.SSOException" %>
<%@ page import="com.iplanet.am.sdk.AMUser"%>
<%@ page import="com.iplanet.am.sdk.AMObject"%>
<%@ page import="com.iplanet.am.sdk.AMTemplate"%>
<%@ page import="com.sun.portal.search.util.Encoder"%>
<%@ page import="com.sun.portal.providers.*, 
		com.sun.portal.providers.context.*,
		 com.sun.portal.providers.jsp.JSPProvider" %>
<%@ page import="com.sun.portal.subscriptions.providers.*"%>

<%@ taglib uri="/tld/jx.tld" prefix="jx" %>
<%@ taglib uri="/tld/desktop.tld" prefix="dt" %>
<%@ taglib uri="/tld/desktopProviderContext.tld" prefix="dtpc" %>
<%@ taglib uri="/tld/search.tld" prefix="search" %>


<dt:obtainChannel channel="$JSPProvider">
<dtpc:providerContext>
<%  
AMUser user = null;
Set categoriesSet = null;
Set discussionsSet = null;
Set savedSearchSet = null;
Map userAttribMap = null;
String newCatName = null;
String newCatTarget = null;
String newCatScope = null;
String newCatSince = null;
String newCatRating = null;
String newServer = null;
String newDatabase = null;
String unsubCat = null;
Set newCategoriesSet = null;
Set newDiscussionsSet = null;
Set newSavedSearchSet = null;
ArrayList catNames = new ArrayList();
ArrayList catNamesDups = new ArrayList();
ArrayList discNames = new ArrayList();
ArrayList discNamesDups = new ArrayList();
ArrayList savedSearchNames = new ArrayList();
ArrayList savedSearchNamesDups = new ArrayList();
boolean subscriptionsService = false;
StringBuffer errorMsg = new StringBuffer();
StringBuffer errorQryStr = new StringBuffer();
try {
        SSOTokenManager mgr = SSOTokenManager.getInstance(); 
        SSOToken token = mgr.createSSOToken(request);
        if (token !=null) {
                AMStoreConnection amstore = new AMStoreConnection(token);
                user = amstore.getUser(token.getPrincipal().getName() );
                subscriptionsService = user.getAssignedServices().contains("SunPortalSubscriptionsService");
                Set userAttribSet = new HashSet();
                userAttribSet.add("sunPortalCategorySubscriptions");
                userAttribSet.add("sunPortalDiscussionSubscriptions");
                userAttribSet.add("sunPortalSavedSearch");
                userAttribMap = user.getAttributes(userAttribSet);
                
        if (userAttribMap != null) {
            categoriesSet = (Set) userAttribMap.get("sunPortalCategorySubscriptions");
            discussionsSet = (Set) userAttribMap.get("sunPortalDiscussionSubscriptions");
            savedSearchSet = (Set) userAttribMap.get("sunPortalSavedSearch");
        } else {
            %><dtpc:logError value="userAttribMap is NULL"/><%
        }
    } else {
        %><dtpc:logError value="SSO Token problem"/><%
    }
} catch (Exception e) {
    %><dtpc:logError value="Cannot get user's subscriptions of its profile"/><%
}

if ((user == null) || (subscriptionsService== false)) {
    if (user == null) {
        %><b>Only registered users may use the subscription service. Please register.</b><%
    } else if (subscriptionsService== false) {
        %><b>You do not have access to the subscription service.<br>
        Please refer to the administrator to assign the susbscription service to your profile.</b>
        <%
    }
} else {
// existing category subscriptions
int catNdx = 0;
int maxCat =  Integer.parseInt((String) ((Set) user.getAttribute("sunPortalMaxCategorySubscriptions")).iterator().next());
if (categoriesSet != null) {
    if(categoriesSet.size() > 0) {
        Iterator categoryIterator = categoriesSet.iterator();
        newCategoriesSet = new HashSet();
        newCatName = null;
        newCatTarget = null;
        newCatScope = null;
        newCatSince = null;
        unsubCat = null;
        while (categoryIterator.hasNext()) {
            categoryIterator.next();
            catNdx++;
            if (catNdx > maxCat) break;
            unsubCat = (String) request.getParameter("_unsub_cat_"+catNdx);
            if (unsubCat != null && unsubCat.equalsIgnoreCase("on")) {
                continue;
            } 
            // check for update of other parameters
            newCatName = (String) request.getParameter("_rename_cat_"+catNdx);
            if (newCatName == null || newCatName.trim().length() == 0) {
                errorMsg.append("<li>renaming category subscription's cannot be empty</li>");
                break;
            }
            String eNewCatName = Encoder.urlEncode(newCatName,"UTF-8");
            if (catNames.contains(eNewCatName)) {
                if (!catNamesDups.contains(eNewCatName)) {
                    errorMsg.append("<li>the category labeled \"").append(newCatName).append("\" label has to be unique</li>");
                    catNamesDups.add(eNewCatName);
                }
            } else {
                catNames.add(eNewCatName);
            }
            newCatTarget = (String) request.getParameter("_retarget_cat_"+catNdx);
            if (newCatTarget == null) newCatTarget = ""; 
            newCatScope = (String) request.getParameter("_rescope_cat_"+catNdx);
            if (newCatScope == null) newCatScope = ""; 
            newCatSince = (String) request.getParameter("_resince_cat_"+catNdx);
            if (newCatSince == null) newCatSince = "0"; 
            newCatRating = (String) request.getParameter("_rerate_cat_"+catNdx);
            if (newCatRating == null) newCatRating = "0";
            newServer = (String) request.getParameter("_reserver_cat_"+catNdx);
            if (newServer == null) newServer = "";
            newDatabase = (String) request.getParameter("_redatabase_cat_"+catNdx);
            if (newDatabase == null) newDatabase = "0";

            newCategoriesSet.add(Encoder.urlEncode(newCatName,"UTF-8")
                +"|"+Encoder.urlEncode(newCatTarget,"UTF-8")
                +"|"+Encoder.urlEncode(newCatScope,"UTF-8")
                +"|"+Encoder.urlEncode(newCatSince,"UTF-8")
                +"|"+Encoder.urlEncode(newCatRating,"UTF-8")
                +"|"+Encoder.urlEncode(newServer,"UTF-8")
                +"|"+Encoder.urlEncode(newDatabase,"UTF-8"));
        } 
    } // end else categoriesSet size = 0
}

// check for new category subscription
newCatName = (String) request.getParameter("_new_name_cat");
if ((newCatName != null) && (catNdx < maxCat)) {
    if (newCatName.trim().length() == 0) {
        errorMsg.append("<li>new category subscription's name cannot be empty");
    } else {
        if (newCategoriesSet == null) {
            newCategoriesSet = new HashSet();
        }
        newCatTarget = (String) request.getParameter("_new_target_cat");
        if (newCatTarget == null) newCatTarget = "";
        newCatScope = (String) request.getParameter("_new_scope_cat");
        if (newCatScope == null) newCatScope = "";
        newCatSince = (String) request.getParameter("_new_since_cat");
        if (newCatSince == null) newCatSince = "0"; 
        newCatRating = (String) request.getParameter("_new_rating_cat");
        if (newCatRating == null) newCatRating = "0"; 
        newServer = (String) request.getParameter("newServer");
        if (newServer == null) newServer = "0"; 
        newDatabase = (String) request.getParameter("newDB");
        if (newDatabase == null) newDatabase = "default"; 
        String eNewCatName = Encoder.urlEncode(newCatName,"UTF-8");
        String eNewCatTarget = Encoder.urlEncode(newCatTarget,"UTF-8");
        if (catNames.contains(eNewCatName)) {
            if (!catNamesDups.contains(eNewCatName)) {
                errorMsg.append("<li>new category subscription labeled \"").append(newCatName).append("\" label must differ from existing ones.</li>");
                errorQryStr.append("&newServer="+Encoder.urlEncode(newServer,"UTF-8")+"&newDB="+Encoder.urlEncode(newDatabase,"UTF-8")+"&newCatSubscription="+eNewCatTarget+"&scope="+Encoder.urlEncode(newCatScope,"UTF-8"));
                catNamesDups.add(eNewCatName);
            }
        } else {
            catNames.add(eNewCatName);
        }
        newCategoriesSet.add(Encoder.urlEncode(newCatName,"UTF-8")
            +"|"+Encoder.urlEncode(newCatTarget,"UTF-8")
            +"|"+Encoder.urlEncode(newCatScope,"UTF-8")
            +"|"+Encoder.urlEncode(newCatSince,"UTF-8")
            +"|"+Encoder.urlEncode(newCatRating,"UTF-8")
            +"|"+Encoder.urlEncode(newServer,"UTF-8")
            +"|"+Encoder.urlEncode(newDatabase,"UTF-8")
            );
    }
}

if (userAttribMap.containsKey("sunPortalCategorySubscriptions")) {
    userAttribMap.remove("sunPortalCategorySubscriptions");
}
if (newCategoriesSet != null) {	
    userAttribMap.put("sunPortalCategorySubscriptions",newCategoriesSet);
}


//--- Discussions
String newDiscName = null;
String newDiscTarget = null;
String newDiscScope = null;
String newDiscSince = null;
String newDiscRating = null;
String unsubDisc = null;

// existing discussion Subscriptions
int discNdx = 0;
int maxDisc =  Integer.parseInt((String) ((Set) user.getAttribute("sunPortalMaxDiscussionSubscriptions")).iterator().next());
if (discussionsSet != null) {
    if(discussionsSet.size() > 0) {
        Iterator discussionIterator = discussionsSet.iterator();
        newDiscussionsSet = new HashSet();
        newDiscName = null;
        newDiscTarget = null;
        newDiscScope = null;
        newDiscSince = null;
        newServer = null;
        newDatabase = null;
        unsubDisc = null;
        while (discussionIterator.hasNext()) {
            discussionIterator.next();
            discNdx++;
            if (discNdx > maxDisc) break;
            unsubDisc = (String) request.getParameter("_unsub_disc_"+discNdx);
            if (unsubDisc != null && unsubDisc.equalsIgnoreCase("on")) {
                continue;
            } 
            // check for update of other parameters
            newDiscName = (String) request.getParameter("_rename_disc_"+discNdx);
            if (newDiscName == null || newDiscName.trim().length() == 0) {
                errorMsg.append("<li>renaming discussion subscription cannot be empty");
                break;
            }
            String eNewDiscName = Encoder.urlEncode(newDiscName,"UTF-8");
            if (discNames.contains(eNewDiscName)) {
                if (!discNamesDups.contains(eNewDiscName)) {
                    errorMsg.append("<li>the discussion labeled \"").append(newDiscName).append("\" label has to be unique</li>");
                    discNamesDups.add(eNewDiscName);
                }
            } else {
                discNames.add(eNewDiscName);
            }

            if (newDiscName == null) newDiscName = ""; 
            newDiscTarget = (String) request.getParameter("_retarget_disc_"+discNdx);
            if (newDiscTarget == null) newDiscTarget = ""; 
            newDiscScope = (String) request.getParameter("_rescope_disc_"+discNdx);
            if (newDiscScope == null) newDiscScope = ""; 
            newDiscSince = (String) request.getParameter("_resince_disc_"+discNdx);
            if (newDiscSince == null) newDiscSince = "0"; 
            newDiscRating = (String) request.getParameter("_rerate_disc_"+discNdx);
            if (newDiscRating == null) newDiscRating = "0";
            newServer = (String) request.getParameter("_reserver_disc_"+discNdx);
            if (newServer == null) newServer = "0";
            newDatabase = (String) request.getParameter("_redatabase_disc_"+discNdx);
            if (newDatabase == null) newDatabase = "0";
            newDiscussionsSet.add(Encoder.urlEncode(newDiscName,"UTF-8")
                +"|"+Encoder.urlEncode(newDiscTarget,"UTF-8")
                +"|"+Encoder.urlEncode(newDiscScope,"UTF-8")
                +"|"+Encoder.urlEncode(newDiscSince,"UTF-8")
                +"|"+Encoder.urlEncode(newDiscRating,"UTF-8")
                +"|"+Encoder.urlEncode(newServer,"UTF-8")
                +"|"+Encoder.urlEncode(newDatabase,"UTF-8"));
        } 
    } // end else discussionsSet size = 0
}

// check for new discussion
newDiscName = (String) request.getParameter("_new_name_disc");
if ((newDiscName != null) && (discNdx < maxDisc)) {
    if (newDiscName.trim().length() == 0) {
        errorMsg.append("<li>new discussion subscription name cannot be empty");
    } else {
        if (newDiscussionsSet == null) {
                newDiscussionsSet = new HashSet();
        }
        newDiscTarget = (String) request.getParameter("_new_target_disc");
        if (newDiscTarget == null) newDiscTarget = "";
        newDiscScope = (String) request.getParameter("_new_scope_disc");
        if (newDiscScope == null) newDiscScope = "";
        newDiscSince = (String) request.getParameter("_new_since_disc");
        if (newDiscSince == null) newDiscSince = "0"; 
        newDiscRating = (String) request.getParameter("_new_rate_disc");
        if (newDiscRating == null) newDiscRating = "0"; 
        newServer = (String) request.getParameter("newServer");
        if (newServer == null) newServer = "0"; 
        newDatabase = (String) request.getParameter("newDB");
        if (newDatabase == null) newDatabase = "discussion"; 
        String eNewDiscName = Encoder.urlEncode(newDiscName,"UTF-8");
        String eNewDiscTarget = Encoder.urlEncode(newDiscTarget,"UTF-8");
        if (discNames.contains(eNewDiscName)) {
            if (!discNamesDups.contains(eNewDiscName)) {
                errorMsg.append("<li>new discussion subscription labeled \"").append(newDiscName).append("\" label must differ from existing ones.</li>");
                errorQryStr.append("&newServer="+Encoder.urlEncode(newServer,"UTF-8")+"&newDB="+Encoder.urlEncode(newDatabase,"UTF-8")+"&newDiscTitle="+eNewDiscName+"&scope="+Encoder.urlEncode(newDiscScope,"UTF-8")+"&newDiscSubscription="+eNewDiscTarget);
                discNamesDups.add(eNewDiscName);
            }
        } else {
                discNames.add(eNewDiscName);
        }
        newDiscussionsSet.add(Encoder.urlEncode(newDiscName,"UTF-8")
            +"|"+Encoder.urlEncode(newDiscTarget,"UTF-8")
            +"|"+Encoder.urlEncode(newDiscScope,"UTF-8")
            +"|"+Encoder.urlEncode(newDiscSince,"UTF-8")
            +"|"+Encoder.urlEncode(newDiscRating,"UTF-8")
            +"|"+Encoder.urlEncode(newServer,"UTF-8")
            +"|"+Encoder.urlEncode(newDatabase,"UTF-8")
            );
    }
}

if (userAttribMap.containsKey("sunPortalDiscussionSubscriptions")) {
    userAttribMap.remove("sunPortalDiscussionSubscriptions");
}
if (newDiscussionsSet != null) {	
    userAttribMap.put("sunPortalDiscussionSubscriptions",newDiscussionsSet);
}

        
//--- Saved Searches
String newSavedSearchName = null;
String newSavedSearchScope = null;
String newSavedSearchSince = null;
String newSavedSearchRating = null;
String unsubSavedSearch = null;

// existing Saved Search Subscriptions
int savedSearchNdx = 0;
int maxSavedSearch =  Integer.parseInt((String) ((Set) user.getAttribute("sunPortalMaxSavedSearch")).iterator().next());
if (savedSearchSet != null) {
    if(savedSearchSet.size() > 0) {
        Iterator savedSearchIterator = savedSearchSet.iterator();
        newSavedSearchSet = new HashSet();
        newSavedSearchName = null;
        newSavedSearchScope = null;
        newSavedSearchSince = null;
        newSavedSearchRating = null;
        newServer = null;
        newDatabase = null;
        unsubSavedSearch = null;
        while (savedSearchIterator.hasNext()) {
            savedSearchIterator.next();
            savedSearchNdx++;
            if (savedSearchNdx > maxSavedSearch) break;
            unsubSavedSearch = (String) request.getParameter("_unsub_savedSearch_"+savedSearchNdx);
            if (unsubSavedSearch != null && unsubSavedSearch.equalsIgnoreCase("on")) {
                continue;
            } 
            // check for update of other parameters
            newSavedSearchName = (String) request.getParameter("_rename_savedSearch_"+savedSearchNdx);
            if (newSavedSearchName == null || newSavedSearchName.trim().length() == 0) {
                errorMsg.append("<li>renaming a saved search cannot be empty");
                break;
            }	 
            String eNewSavedSearchName = Encoder.urlEncode(newSavedSearchName,"UTF-8");
            if (savedSearchNames.contains(eNewSavedSearchName)) {
                if (!savedSearchNamesDups.contains(eNewSavedSearchName)) {
                    errorMsg.append("<li>the saved search labeled \"").append(newSavedSearchName).append("\" label has to be unique</li>");
                    savedSearchNamesDups.add(eNewSavedSearchName);
                }
            } else {
                savedSearchNames.add(eNewSavedSearchName);
            }
            newSavedSearchScope = (String) request.getParameter("_rescope_savedSearch_"+savedSearchNdx);
            if (newSavedSearchScope == null) newSavedSearchScope = ""; 
            newSavedSearchSince = (String) request.getParameter("_resince_savedSearch_"+savedSearchNdx);
            if (newSavedSearchSince == null) newSavedSearchSince = "0"; 
            newSavedSearchRating = (String) request.getParameter("_rerate_savedSearch_"+savedSearchNdx);
            if (newSavedSearchRating == null) newSavedSearchRating = "0";
            newServer = (String) request.getParameter("_reserver_savedSearch_"+savedSearchNdx);
            if (newServer == null) newServer = "";
            newDatabase = (String) request.getParameter("_redatabase_savedSearch_"+savedSearchNdx);
            if (newDatabase == null) newDatabase = "default";

            newSavedSearchSet.add(Encoder.urlEncode(newSavedSearchName,"UTF-8")
                +"|"+Encoder.urlEncode(newSavedSearchScope,"UTF-8")
                +"|"+Encoder.urlEncode(newSavedSearchSince,"UTF-8")
                +"|"+Encoder.urlEncode(newSavedSearchRating,"UTF-8")
                +"|"+Encoder.urlEncode(newServer,"UTF-8")
                +"|"+Encoder.urlEncode(newDatabase,"UTF-8"));
        }
    } // end else savedSearchSet size = 0
}

// check for new saved Search
newSavedSearchName = (String) request.getParameter("_new_name_savedSearch");
if ((newSavedSearchName != null) && (savedSearchNdx < maxSavedSearch)) {
    if (newSavedSearchName.trim().length() == 0) {
        errorMsg.append("<li>renaming a saved search cannot be empty");
    } else {
        if (newSavedSearchSet == null) {
            newSavedSearchSet = new HashSet();
        }
        newSavedSearchScope = (String) request.getParameter("_new_scope_savedSearch");
        if (newSavedSearchScope == null) newSavedSearchScope = "";
        newSavedSearchSince = (String) request.getParameter("_new_since_savedSearch");
        if (newSavedSearchSince == null) newSavedSearchSince = "0"; 
        newSavedSearchRating = (String) request.getParameter("_new_rating_savedSearch");
        if (newSavedSearchRating == null) newSavedSearchRating = "0"; 
        newServer = (String) request.getParameter("newServer");
        if (newServer == null) newServer = "0"; 
        newDatabase = (String) request.getParameter("newDB");
        if (newDatabase == null) newDatabase = "default"; 
        String eNewSavedSearchName = Encoder.urlEncode(newSavedSearchName,"UTF-8");
        if (savedSearchNames.contains(eNewSavedSearchName)) {
            if (!savedSearchNamesDups.contains(eNewSavedSearchName)) {
                errorMsg.append("<li>new saved search subscription labeled \"").append(newSavedSearchName).append("\" label must differ from existing ones.</li>");
                errorQryStr.append("&newServer="+Encoder.urlEncode(newServer,"UTF-8")+"&newDB="+Encoder.urlEncode(newDatabase,"UTF-8")+"&title="+eNewSavedSearchName+"&newSavedSearchSubscription="+eNewSavedSearchName+"&scope="+Encoder.urlEncode(newSavedSearchScope,"UTF-8"));
                savedSearchNamesDups.add(eNewSavedSearchName);
            }
        } else {
            savedSearchNames.add(eNewSavedSearchName);
        }
        newSavedSearchSet.add(Encoder.urlEncode(newSavedSearchName,"UTF-8")
            +"|"+Encoder.urlEncode(newSavedSearchScope,"UTF-8")
            +"|"+Encoder.urlEncode(newSavedSearchSince,"UTF-8")
            +"|"+Encoder.urlEncode(newSavedSearchRating,"UTF-8")
            +"|"+Encoder.urlEncode(newServer,"UTF-8")
            +"|"+Encoder.urlEncode(newDatabase,"UTF-8")
            );
    }
}

if (userAttribMap.containsKey("sunPortalSavedSearch")) {
    userAttribMap.remove("sunPortalSavedSearch");
}
if (newSavedSearchSet != null) {	
    userAttribMap.put("sunPortalSavedSearch",newSavedSearchSet);
}
//storing updated user data
if ((newDiscussionsSet != null) ||
    (newCategoriesSet != null) ||
    (newSavedSearchSet != null)) {	
    if (errorMsg.length() == 0) {
        user.setAttributes(userAttribMap);
        try { 
            user.store();
        } catch (AMException ame) {
            %><dtpc:logError value="Failed to store user"/><%
        }
    }
} 

} // end of else : user is rightfully editing subscription properties

if (errorMsg.length() != 0) {
    Map pathInfo = new HashMap();
    pathInfo.put("action", "edit");
    pathInfo.put("provider", "JSPEditContainer");
    pathInfo.put("targetprovider", "Subscriptions");
    pathInfo.put("last", "false");
    pageContext.setAttribute("pathInfo", pathInfo);
    StringBuffer eErrorMsg = new StringBuffer(Encoder.urlEncode(errorMsg.toString(),"UTF-8"));
    if (errorQryStr.toString().trim().length() != 0) {
        eErrorMsg.append(errorQryStr.toString());
    }
    Map queryInfo = new HashMap();
    queryInfo.put("error",eErrorMsg.toString());
    pageContext.setAttribute("queryInfo", queryInfo);
%>
<dt:obtainChannel channel="$JSPProvider">
    <dtpc:providerContext>
        <dtpc:getDesktopURL pathinfo="$pathInfo" querymap="$queryInfo" id="errorRedirect"/>
    </dtpc:providerContext>
</dt:obtainChannel>
<jx:declare id="errorRedirect" type="java.lang.String"/>
<%
    response.sendRedirect(errorRedirect);
} else {
%>
    <dt:getName id="channelName" scope="request"/>
<% 
    // force the Subscriptions channel to refresh
    String channelName=(String)pageContext.getAttribute("channelName",PageContext.REQUEST_SCOPE);  
    JSPProvider p=(JSPProvider)pageContext.getAttribute("JSPProvider");
    p.getProviderContext().contentChanged(channelName);
    
    // redirecting request
%><dtpc:getDesktopURL id="successRedirect"/>
<jx:declare id="successRedirect" type="java.lang.String"/>

<%--
<dtpc:logError value="<%=(String)pageContext.getAttribute("url")%>"/>
    response.sendRedirect((String)pageContext.getAttribute("url")/* p.getProviderContext().getDesktopURL(request)*/);
--%>
    response.sendRedirect(successRedirect);

<%
}
%>

</dtpc:providerContext>
</dt:obtainChannel>
