<%-- 
  Copyright 2003 Sun Microsystems, Inc. All rights reserved. 
  Use is subject to license terms.
 --%> 
<%@ page import="java.util.Enumeration" %>
<%@ page import="java.util.*,java.text.DateFormat,java.text.SimpleDateFormat" %>
<%@ page import="com.iplanet.sso.SSOTokenManager" %>
<%@ page import="com.iplanet.sso.SSOToken" %>
<%@ page import="com.sun.identity.sm.ServiceSchema" %>
<%@ page import="com.sun.identity.sm.ServiceSchemaManager" %>
<%@ page import="com.sun.identity.sm.AttributeSchema" %>
<%@ 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.sun.portal.search.soif.SOIF"%>
<%@ page import="com.sun.portal.search.providers.SearchContext"%>
<%@ page import="com.sun.portal.search.util.Decoder"%>
<%@ page import="com.sun.portal.search.util.Encoder"%>
<%@ 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" %>
<%@ taglib uri="/tld/desktopTheme.tld" prefix="dttheme" %>

<script LANGUAGE=JavaScript>
function displayHit(url) {   
    var fullurl = document.URL;
    targeturl = fullurl.split( "dt" )[0];
    adjustedUrl = (url.indexOf("http") != -1)? url : targeturl + url;

    if (window.opener != null) {
       window.open(adjustedUrl, 'ps_main');
    } else {
			window.location = adjustedUrl;
		}
}
</SCRIPT>

<dt:obtainChannel channel="$JSPProvider">
<dtpc:providerContext>
	<dtpc:getSessionID id="sessionID"/>
	<dtpc:getLocale id="locale"/>
	<jx:declare id="locale" type="Locale"/>

	<dttheme:getAttribute name="titleBarColor" id="subSectionTitle" scope="request"/> 
	<dttheme:getAttribute name="borderColor" id="subSectionHeader" scope="request"/> 
	<dttheme:getAttribute name="bgColor" id="subSection" scope="request"/>
	<jx:declare id="subSectionTitle" type="java.lang.String"/>
	<jx:declare id="subSectionHeader" type="java.lang.String"/>
	<jx:declare id="subSection" type="java.lang.String"/>
	<STYLE type="text/css">
   .subSectionTitle { background: <%=subSectionTitle%>;}
	 .subSectionHeader { background: <dttheme:getAttribute name="tabColor" default="#C0C0C0"/>; 
	 															color: <dttheme:getAttribute name="tabFontColor" default="#000000"/>}
	 .subSection {border-bottom: thin solid <%=subSectionHeader%>; background: <%=subSection%>}
	</STYLE>

 <dtpc:getStringProperty key="fontFace1" id="fontFace"/>
<jx:declare id="fontFace" type="java.lang.String"/>
	<%
	Set searchServerInstances = null; 
	ServiceSchema subscriptionsUserSvcSchema = null; 

	try { 
		SSOTokenManager mgr = SSOTokenManager.getInstance(); 
		SSOToken token = mgr.createSSOToken(request);
		pageContext.setAttribute("accessToken", token); 
		if (token !=null) {
			ServiceSchemaManager schemaMgr = new ServiceSchemaManager("SunPortalSearchService", token); 
			ServiceSchema searchGlobalSvcSchema = schemaMgr.getGlobalSchema(); 
			if (searchGlobalSvcSchema != null) { 
				AttributeSchema as = searchGlobalSvcSchema.getAttributeSchema("sunPortalSearchInstances"); 
				if (as != null) { 
					searchServerInstances = as.getDefaultValues(); 
				} 
			} 
		} 
	} catch (Exception e) {
		%><b> Cannot access search service</b> 
		<%
	}
	// setting the target search server
	String srchServer = ""; 
	if (searchServerInstances != null) { 
		Iterator ss = searchServerInstances.iterator(); 
		if (ss.hasNext()) { 
			srchServer = (String)ss.next() + "/search";  //selecting the 1st search server
			}
		}
		pageContext.setAttribute("searchServer", srchServer);
		// getting the subscriptions detail
		AMUser user = null;
		Set categoriesSet = null;
		Set discussionsSet = null;
		Set savedSearchSet = null;
		SearchSubscription subItem = null;
		HashMap subElements = null;
		boolean subscriptionsService= false;
		try {
			SSOToken token = (SSOToken) pageContext.getAttribute("accessToken");
			if (token !=null) {
				AMStoreConnection amstore = new AMStoreConnection(token);
				user = amstore.getUser(token.getPrincipal().getName() );
				subscriptionsService = user.getAssignedServices().contains("SunPortalSubscriptionsService");
				categoriesSet = (Set) user.getAttribute("sunPortalCategorySubscriptions");
				discussionsSet = (Set) user.getAttribute("sunPortalDiscussionSubscriptions");
				savedSearchSet = (Set) user.getAttribute("sunPortalSavedSearch");
			} else {
			%><dtpc:logError value="SSO Token problem"/><%
			} 
		} 
		catch (Exception e) {
		%><dptc: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 {
		%>
		<table border="0" width="100%" cellpadding="1" cellspacing="0">
			<tr>
				<td valign="top" align="left" colspan="3" class="subSectionHeader">Categories</td>
			</tr>
		<%
		if (categoriesSet != null) {
			if (categoriesSet.size() > 0) {
				int maxCat = Integer.parseInt((String) ((Set) user.getAttribute("sunPortalMaxCategorySubscriptions")).iterator().next());
				Iterator categoryIterator = categoriesSet.iterator();
				int catNdx = 0;
				DateFormat df = new SimpleDateFormat("MM/dd/yy");
				while (categoryIterator.hasNext()) {
					String catSubStr = (String) categoryIterator.next();
					catNdx++;
					if (catNdx > maxCat) break;
					//parse the subscription
					subItem = new SearchSubscription("http://panoramic.red.iplanet.com/portal/search",
						Subscription.CATEGORY_SRCH_SUB, catSubStr,
                                                "hl-url,hl-title,title,hl-description,score,classification,hl-classification,rd-rating");
					subItem.parse();
					subElements = subItem.getElements();
					String catName = (String) subElements.get("name");
					String catTarget = (String) subElements.get("target");
					String catScope = (String) subElements.get("scope");
					String catSince = (String) subElements.get("since");
					String catRating = (String) subElements.get("rating");
					String catServer = (String) subElements.get("server");
					String catDatabase = (String) subElements.get("database");
					if (catName == null) {
						catName="";
						continue;
					}
				%>
						<tr>
						  <td class="subSection" width="1%"><br></td>
							<td class="subSection" align="left" nowrap="nowrap">
									<%=(String) SearchContext.htmlEncode(catName)%>
							</td>
							<td class="subSection" align="right">
									<%-- created the search query --%>
									<search:searchContext>
									<search:setQueryLanguage ql="search"/>
									<search:setRDMServer rdmServer="<%=catServer%>"/>
									<search:setRDMType rdmType= "rd-request"/>
									<search:setViewHits viewHits="0"/>
									<search:setViewAttributes viewAttributes="title"/>
									<search:setSessionID sessionID="$sessionID"/>
									<search:setSearchAll searchAll="false"/>
									<search:setDatabase database= "<%=catDatabase%>"/> 
									<search:setQuery query="<%=catScope%>"/>
									<search:setCategory category="<%=catTarget%>"/>
									<%
										// getting the lapse of time for new docs 
										StringBuffer scopeSB = new StringBuffer();
										ArrayList l = new ArrayList();
										HashMap h;
										if (catScope  != null) {
												h = new HashMap();
												h.put(SearchContext.OPERAND, "");
												h.put(SearchContext.OPERATION, SearchContext.ALL);
												h.put(SearchContext.VALUE, catScope);
												l.add(h);
												scopeSB.append(catScope);
												scopeSB.append(" ");
										}
										if (!catSince.equals("0")) {
											h = new HashMap();
											h.put(SearchContext.OPERAND, "RD-Last-Changed");
											h.put(SearchContext.OPERATION, SearchContext.GREATER);
											Calendar c1 = new GregorianCalendar();
											String d1 = df.format(c1.getTime());
											if (catSince.equals("7")) {
													c1.add(Calendar.DATE, -7);
											}
											if (catSince.equals("30")) {
													c1.roll(Calendar.MONTH, false);
											}
											if (catSince.equals("180")) {
													c1.add(Calendar.MONTH, -6);
											}
											if (catSince.equals("365")) {
													c1.roll(Calendar.YEAR, false);
											}
											String d2 = df.format(c1.getTime());
											h.put(SearchContext.VALUE, d2);
											l.add(h);
											catScope += " <AND> (RD-Last-Changed  >" + d2+")";
										}
										%>
										<search:setCriteria criteria="<%=l%>"/>
									<%-- execute the search --%>
									<search:executeSearch/>
									<search:getNoHits id="noHits"/>
									<jx:declare id="noHits" type="java.lang.Boolean"/>
									<%
									 if (noHits.booleanValue() != true) {
									%>
									<search:getHitCount id="hitsCount"/>
									<jx:declare id="hitsCount" type="java.lang.Integer"/>
									<%
									Map pathInfo = new HashMap();
									pathInfo.put("action", "content");
									pathInfo.put("provider", "JSPDynamicSingleContainer");
									pathInfo.put("JSPDynamicSingleContainer.selectedChannel", "Search");
									pathInfo.put("last", "false");
									pageContext.setAttribute("pathInfo", pathInfo);
									Map queryInfo = new HashMap();
									queryInfo.put("mode","browse");
									queryInfo.put("scope",Encoder.urlEncode(catScope,"UTF-8"));
									queryInfo.put("scat","cat");
									queryInfo.put("browseCategory",Encoder.urlEncode(catTarget,"UTF-8"));
									pageContext.setAttribute("queryInfo", queryInfo);
									%>
									<a href='javascript:void( 0);' onclick="displayHit('<dtpc:getDesktopURL pathinfo="$pathInfo" querymap="$queryInfo"/>');return false;"><%=hitsCount%></a>&nbsp;
									<%
									} else {
									%>
									0&nbsp;<br>
									<%
									}
									%>
									</search:searchContext>
							</td>
						</tr>
						<%
						} // end of while on categories
			} else { // end of if there is at least one category
				%><tr>
						<td width="1%"><br></td>
						<td align="left" colspan="2">No category Subscription defined</td>
					</tr>
				<%
			}
		} else { // end of if categoriesSet != null
				%><tr>
						<td width="1%"><br></td>
						<td align="left" colspan="2">No category Subscription defined</td>
					</tr>
				<%
		}
		%>
			<tr>
				<td valign="top" align="left" colspan="3" class="subSectionHeader">Discussions</td>
			</tr>
		<%
		if (discussionsSet != null) {
			if (discussionsSet.size() > 0) {
				int maxDisc = Integer.parseInt((String) ((Set) user.getAttribute("sunPortalMaxDiscussionSubscriptions")).iterator().next());
				Iterator discussionIterator = discussionsSet.iterator();
				int discNdx = 0;
				DateFormat df = new SimpleDateFormat("MM/dd/yy");
				while (discussionIterator.hasNext()) {
					String discSubStr = (String) discussionIterator.next();
					discNdx++;
					if (discNdx > maxDisc) break;
					//parse the subscription
					subItem = new SearchSubscription("http://panoramic.red.iplanet.com/portal/search",
						Subscription.DISCUSSION_SRCH_SUB, discSubStr,
                                                "hl-url,hl-title,title,hl-description,score,classification,hl-classification,rd-rating,hl-rd-reference-id, rd-reference-id");
					subItem.parse(); 
					subElements = subItem.getElements();
					String discName = (String) subElements.get("name");
					String discTarget = (String) subElements.get("target");
					String discScope = (String) subElements.get("scope");
					String discRating = (String) subElements.get("rating");
					String discSince = (String) subElements.get("since");
					String discServer = (String) subElements.get("server");
					String discDatabase = (String) subElements.get("database");
					if (discName == null) {
						discName="";
						continue;
					}
				%>
						<tr>
						  <td class="subSection" width="1%"><br></td>
							<td class="subSection" align="left" nowrap="nowrap">
									<%=SearchContext.htmlEncode(discName)%>
							</td>
							<td class="subSection" align="right">
									<search:searchContext>
										<search:setQueryLanguage ql="search"/>
										<search:setRDMServer rdmServer="<%=discServer%>"/>
										<search:setRDMType rdmType= "rd-request"/>
										<search:setViewHits viewHits="0"/>
										<search:setViewAttributes viewAttributes="RD-Reference-Id,RD-Rating"/>
										<search:setSessionID sessionID="$sessionID"/>
										<search:setDatabase database="<%=discDatabase%>"/>
										<%--<search:setQuery query="<%=discScope%>"/>--%>
										<%
											StringBuffer scopeSB = new StringBuffer(); 
											ArrayList l = new ArrayList();
											HashMap h;
											if (discScope != null) {
											    h = new HashMap();
											    h.put(SearchContext.OPERAND, "");
											    h.put(SearchContext.OPERATION, SearchContext.ALL);
											    h.put(SearchContext.VALUE, discScope);
											    l.add(h);
											    scopeSB.append(discScope);
											    scopeSB.append(" ");
											}

											if (discTarget != null && (!discTarget.equals("ROOT"))) {
											    // ROOT not needed since we are searching within discussion database 
											    h = new HashMap();
											    h.put(SearchContext.OPERAND, "RD-Reference-Id");
											    h.put(SearchContext.OPERATION, SearchContext.CONTAIN);
											    h.put(SearchContext.VALUE, discTarget);
											    l.add(h);
											    scopeSB.append(" <AND> (RD-Reference-Id  <CONTAINS>");
											    scopeSB.append(discTarget);
											    scopeSB.append(") ");
											}
											if (discRating != null) {
												int rtg = -1;
												try {
											    rtg = new Integer(discRating).intValue();
												} catch (NumberFormatException e) {
													rtg=-1;													
												}
											    if (rtg > -1) {
												h = new HashMap();
												h.put(SearchContext.OPERAND, "RD-Rating");
												h.put(SearchContext.OPERATION, SearchContext.GREATER);
												h.put(SearchContext.VALUE, Integer.toString(rtg-1));
												l.add(h);
												scopeSB.append(" <AND> (RD-Rating  > ");
												scopeSB.append(Integer.toString(rtg-1));
												scopeSB.append(")");
											    }
											}
											if (!discSince.equals("0")) {
											    h = new HashMap();
											    h.put(SearchContext.OPERAND, "RD-Last-Changed");
											    h.put(SearchContext.OPERATION, SearchContext.GREATER);
											    Calendar c1 = new GregorianCalendar();
											    String d1 = df.format(c1.getTime());
											    if (discSince.equals("7")) {
													    c1.add(Calendar.DATE, -7);
											    }
											    if (discSince.equals("30")) {
													    c1.roll(Calendar.MONTH, false);
											    }
											    if (discSince.equals("180")) {
													    c1.add(Calendar.MONTH, -6);
											    }
											    if (discSince.equals("365")) {
													    c1.roll(Calendar.YEAR, false);
											    }
											    String d2 = df.format(c1.getTime());
											    h.put(SearchContext.VALUE, d2);
												    l.add(h);
												    scopeSB.append(" <AND> (RD-Last-Changed  >" + d2+")");
											}
											%>
										<search:setCriteria criteria="<%=l%>"/>
										
										<search:executeSearch/>
										
										<search:getNoHits id="noHits"/>
										<jx:declare id="noHits" type="java.lang.Boolean"/>
									<%
										 if (noHits.booleanValue() != true) {
									%>
										<search:getHitCount id="hitsCount"/>
										<jx:declare id="hitsCount" type="java.lang.Integer"/>
									<%
									Map pathInfo = new HashMap();
									pathInfo.put("action", "content");
									pathInfo.put("provider", "JSPDynamicSingleContainer");
									pathInfo.put("JSPDynamicSingleContainer.selectedChannel", "Search");
									pathInfo.put("last", "false");
									pageContext.setAttribute("pathInfo", pathInfo);
									Map queryInfo = new HashMap();
									queryInfo.put("database",discDatabase);
									queryInfo.put("scope",Encoder.urlEncode(scopeSB.toString(),"UTF-8"));
									pageContext.setAttribute("queryInfo", queryInfo);
									%>
									<a href='javascript:void( 0);' onclick="displayHit('<dtpc:getDesktopURL pathinfo="$pathInfo" querymap="$queryInfo"/>');return false;"><%=hitsCount%></a>&nbsp;
									<%
										} else {
										%>
									0&nbsp;<br>
									<%
										}
									%>
									</search:searchContext>
							</td>
						</tr>
						<%
						} // end of while on discussions
						%>
			</tr>
		<%
			} else { // end of if there is at least one discussion
				%>
					<tr>
						<td><br></td>
						<td align="left" colspan="2">No discussion Subscription defined</td>
					</tr>
				<%
			}
		} else { // end of if discussionsSet != null
				%>
					<tr>
						<td><br></td>
						<td align="left" colspan="2">No discussion Subscription defined</td>
					</tr>
				<%
		}
		%>
			<tr>
				<td valign="top" align="left" colspan="3" class="subSectionHeader">Saved Searches</td>
			</tr>
		<%
		if (savedSearchSet != null) {
			if (savedSearchSet.size() > 0) {
				int maxSavedSearch = Integer.parseInt((String) ((Set) user.getAttribute("sunPortalMaxSavedSearch")).iterator().next());

				Iterator savedSearchIterator = savedSearchSet.iterator();
				int savedSearchNdx = 0;
				DateFormat df = new SimpleDateFormat("MM/dd/yy");
				while (savedSearchIterator.hasNext()) {
					String savedSearchSubStr = (String) savedSearchIterator.next();
					savedSearchNdx++;
					if (savedSearchNdx > maxSavedSearch) break;
					//parse the subscription
					subItem = new SearchSubscription("http://panoramic.red.iplanet.com/portal/search",
						Subscription.SAVED_SRCH_SUB, savedSearchSubStr,
                                                "hl-url,hl-title,title,hl-description,score,classification,hl-classification,rd-rating");
					subItem.parse(); 
					subElements = subItem.getElements();

					String savedSearchName = (String) subElements.get("name");
					String savedSearchScope = (String) subElements.get("scope");
					String savedSearchSince = (String) subElements.get("since");
					String savedSearchRating = (String) subElements.get("rating");
					String savedSearchServer = (String) subElements.get("server");
					String savedSearchDatabase =  (String) subElements.get("database");
					if (savedSearchName == null) {
						savedSearchName="";
						continue;
					}
				%>
						<tr>
							<td  class="subSection" width="1%"><br></td>
							<td  class="subSection" align="left">
									<%=SearchContext.htmlEncode(savedSearchName)%>
							</td>
							<td  class="subSection"align="right">
									<search:searchContext>
										<search:setQueryLanguage ql="search"/>
										<search:setRDMServer rdmServer="<%=savedSearchServer%>"/>
										<search:setRDMType rdmType= "rd-request"/>
										<search:setViewHits viewHits="0"/>
										<search:setViewAttributes viewAttributes="RD-Reference-Id"/>
										<search:setSessionID sessionID="$sessionID"/>
										<search:setDatabase database="<%=savedSearchDatabase%>"/>
										<%--<search:setQuery query="<%=savedSearchScope%>"/>--%>
										<%
											StringBuffer scopeSB = new StringBuffer();
											ArrayList l = new ArrayList();
											HashMap h;
											if (savedSearchScope != null) {
													h = new HashMap();
													h.put(SearchContext.OPERAND, "");
													h.put(SearchContext.OPERATION, SearchContext.ALL);
													h.put(SearchContext.VALUE, savedSearchScope);
													l.add(h);
													scopeSB.append(savedSearchScope);
													scopeSB.append(" ");
											}
											if (!savedSearchSince.equals("0")) {
												h = new HashMap();
												h.put(SearchContext.OPERAND, "RD-Last-Changed");
												h.put(SearchContext.OPERATION, SearchContext.GREATER);
												Calendar c1 = new GregorianCalendar();
												String d1 = df.format(c1.getTime());
												if (savedSearchSince.equals("7")) {
														c1.add(Calendar.DATE, -7);
												}
												if (savedSearchSince.equals("30")) {
														c1.roll(Calendar.MONTH, false);
												}
												if (savedSearchSince.equals("180")) {
														c1.add(Calendar.MONTH, -6);
												}
												if (savedSearchSince.equals("365")) {
														c1.roll(Calendar.YEAR, false);
												}
												String d2 = df.format(c1.getTime());
												h.put(SearchContext.VALUE, d2);
												l.add(h);
											}
											%>
										<search:setCriteria criteria="<%=l%>"/>
										
										<search:executeSearch/>
										<search:getNoHits id="noHits"/>
										<jx:declare id="noHits" type="java.lang.Boolean"/>
									<%
										 if (noHits.booleanValue() != true) {
									%>
										<search:getHitCount id="hitsCount"/>
										<jx:declare id="hitsCount" type="java.lang.Integer"/>
									<%
									Map pathInfo = new HashMap();
									pathInfo.put("action", "content");
									pathInfo.put("provider", "JSPDynamicSingleContainer");
									pathInfo.put("JSPDynamicSingleContainer.selectedChannel", "Search");
									pathInfo.put("last", "false");
									pageContext.setAttribute("pathInfo", pathInfo);
									Map queryInfo = new HashMap();
									queryInfo.put("scope",Encoder.urlEncode(savedSearchScope,"UTF-8"));
									pageContext.setAttribute("queryInfo", queryInfo);
									%>
									<a href='javascript:void( 0);' onclick="displayHit('<dtpc:getDesktopURL pathinfo="$pathInfo" querymap="$queryInfo"/>');return false;"><%=hitsCount%></a>&nbsp;
									<%
										} else {
										%>
									0&nbsp;<br>
									<%
										}
									%>
									</search:searchContext>
							</td>
						</tr>
						<%
						} // end of while on saved search
			} else { // end of if there is at least one saved search
				%>
					<tr>
						<td><br></td>
						<td align="left" colspan="2">No saved search Subscription defined</td>
					</tr>
				<%
			}
		} else { // end of if savedSearchSet != null
				%>
					<tr>
						<td><br></td>
						<td align="left" colspan="2">No saved search Subscription defined</td>
					</tr>
				<%
		}
		%>
		</table>
	<%
	}
	%>
	</dtpc:providerContext>
</dt:obtainChannel>

