<%
/**
 * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */
%>

<%
String keywords = ParamUtil.getString(request, "keywords");
String tag = ParamUtil.getString(request, "tag");
String searchRepositoryURL = ParamUtil.getString(request, "searchRepositoryURL");
String license = ParamUtil.getString(request, "license");
String installStatus = ParamUtil.getString(request, "installStatus", PluginPackageImpl.STATUS_NOT_INSTALLED_OR_OLDER_VERSION_INSTALLED);
%>

<style type="text/css">
	.search-params .aui-field {
		float: left;
		margin-bottom: 1em;
	}
</style>

<liferay-ui:tabs
	names="portlet-plugins,theme-plugins,layout-template-plugins,hook-plugins,web-plugins"
	param="tabs2"
	url="<%= portletURLString %>"
/>

<%
try {
%>

	<aui:fieldset cssClass="aui-field-row search-params">
		<aui:input name="keywords" size="30" type="text" value="<%= HtmlUtil.escape(keywords) %>" />

		<aui:select name="tag">
			<aui:option label="all" value="" />

			<%
			Iterator itr = PluginPackageUtil.getAvailableTags().iterator();

			while (itr.hasNext()) {
				String curTag = (String)itr.next();
			%>

				<aui:option label="<%= curTag %>" selected="<%= tag.equals(curTag) %>" />

			<%
			}
			%>

		</aui:select>

		<aui:select label="repository" name="searchRepositoryURL">
			<aui:option label="all" value="" />

			<%
			String[] repositoryURLs = PluginPackageUtil.getRepositoryURLs();

			for (int i = 0; i < repositoryURLs.length; i++) {
				String curRepositoryURL = repositoryURLs[i];
			%>

				<aui:option label="<%= curRepositoryURL %>" selected="<%= searchRepositoryURL.equals(curRepositoryURL) %>" />

			<%
			}
			%>

		</aui:select>

		<aui:select name="installStatus">
			<aui:option label="not-installed-or-older-version-installed" selected="<%= (installStatus.equals(PluginPackageImpl.STATUS_NOT_INSTALLED_OR_OLDER_VERSION_INSTALLED)) %>" value="<%= PluginPackageImpl.STATUS_NOT_INSTALLED_OR_OLDER_VERSION_INSTALLED %>" />
			<aui:option label="older-version-installed" selected="<%= (installStatus.equals(PluginPackageImpl.STATUS_OLDER_VERSION_INSTALLED)) %>" value="<%= PluginPackageImpl.STATUS_OLDER_VERSION_INSTALLED %>" />
			<aui:option label="not-installed" selected="<%= (installStatus.equals(PluginPackageImpl.STATUS_NOT_INSTALLED)) %>" value="<%= PluginPackageImpl.STATUS_NOT_INSTALLED %>" />
			<aui:option label="all" selected="<%= (installStatus.equals(PluginPackageImpl.STATUS_ALL)) %>" value="<%= PluginPackageImpl.STATUS_ALL %>" />
		</aui:select>

		<aui:button-row>
			<aui:button type="submit" value="search" />
		</aui:button-row>
	</aui:fieldset>

	<div class="separator"><!-- --></div>

	<%
	String orderByCol = ParamUtil.getString(request, "orderByCol");
	String orderByType = ParamUtil.getString(request, "orderByType");

	if (Validator.isNotNull(orderByCol) && Validator.isNotNull(orderByType)) {
		portalPrefs.setValue(PortletKeys.PLUGIN_INSTALLER, "plugin-packages-order-by-col", orderByCol);
		portalPrefs.setValue(PortletKeys.PLUGIN_INSTALLER, "plugin-packages-order-by-type", orderByType);
	}
	else {
		orderByCol = portalPrefs.getValue(PortletKeys.PLUGIN_INSTALLER, "plugin-packages-order-by-col", "modified-date");
		orderByType = portalPrefs.getValue(PortletKeys.PLUGIN_INSTALLER, "plugin-packages-order-by-type", "desc");
	}

	List<String> headerNames = new ArrayList<String>();

	headerNames.add(pluginType + "-plugin");
	headerNames.add("trusted");
	headerNames.add("tags");
	headerNames.add("installed-version");
	headerNames.add("available-version");
	headerNames.add("modified-date");

	Map orderableHeaders = new HashMap();

	orderableHeaders.put(pluginType + "-plugin", Field.TITLE);
	orderableHeaders.put("modified-date", "modified-date");

	SearchContainer searchContainer = new SearchContainer(renderRequest, null, null, SearchContainer.DEFAULT_CUR_PARAM, SearchContainer.DEFAULT_DELTA, portletURL, headerNames, LanguageUtil.get(pageContext, "no-" + pluginType + "-plugins-were-found"));

	searchContainer.setOrderableHeaders(orderableHeaders);
	searchContainer.setOrderByCol(orderByCol);
	searchContainer.setOrderByType(orderByType);

	List results = PluginPackageUtil.search(keywords, pluginType, tag, license, searchRepositoryURL, installStatus, QueryUtil.ALL_POS, QueryUtil.ALL_POS).toList();

	DocumentComparator docComparator = null;

	if (orderByType.equals("desc")) {
		docComparator = new DocumentComparator(false, false);
	}
	else {
		docComparator = new DocumentComparator();
	}

	if (orderByCol.equals("modified-date")) {
		docComparator.addOrderBy("modified-date");
	}
	else {
		docComparator.addOrderBy(Field.TITLE);
		docComparator.addOrderBy("version");
	}

	results = ListUtil.sort(results, docComparator);

	int total = results.size();

	searchContainer.setTotal(total);

	results = ListUtil.subList(results, searchContainer.getStart(), searchContainer.getEnd());

	searchContainer.setResults(results);

	List resultRows = searchContainer.getResultRows();

	for (int i = 0; i < results.size(); i++) {
		Document doc = (Document)results.get(i);

		String pluginPackageName = doc.get(Field.TITLE);
		String pluginPackageModuleId = doc.get("moduleId");
		String pluginPackageGroupId = doc.get("groupId");
		String pluginPackageArtifactId = doc.get("artifactId");
		String pluginPackageAvailableVersion = doc.get("version");
		Date pluginPackageModifiedDate = doc.getDate(Field.MODIFIED);
		String pluginPackageTags = StringUtil.merge(doc.getValues("tag"), StringPool.COMMA + StringPool.SPACE);
		String pluginPackageShortDescription = doc.get("shortDescription");
		String pluginPackageChangeLog = doc.get("changeLog");
		String pluginPackageRepositoryURL = doc.get("repositoryURL");

		// The value for pluginPackage should never be null except when Lucene
		// is out of sync as in LEP-4783 or when the plugin was not installed
		// from a repository.

		PluginPackage pluginPackage = null;

		if (!pluginPackageRepositoryURL.startsWith(RemotePluginPackageRepository.LOCAL_URL)) {
			pluginPackage = PluginPackageUtil.getPluginPackageByModuleId(pluginPackageModuleId, pluginPackageRepositoryURL);
		}

		PluginPackage installedPluginPackage = PluginPackageUtil.getLatestInstalledPluginPackage(pluginPackageGroupId, pluginPackageArtifactId);

		ResultRow row = new ResultRow(doc, pluginPackageModuleId, i);

		PortletURL rowURL = renderResponse.createRenderURL();

		rowURL.setParameter("struts_action", "/plugin_installer/view");
		rowURL.setParameter("tabs1", tabs1);
		rowURL.setParameter("tabs2", tabs2);
		rowURL.setParameter("redirect", currentURL);
		rowURL.setParameter("moduleId", pluginPackageModuleId);
		rowURL.setParameter("repositoryURL", pluginPackageRepositoryURL);

		// Name, screenshots, and short description

		StringBundler sb = new StringBundler();

		if (pluginPackage != null) {
			sb.append("<a href='");
			sb.append(rowURL.toString());
			sb.append("'>");

			if (tabs2.equals("layout-templates") || tabs2.equals("themes")) {
				List screenshots = pluginPackage.getScreenshots();

				if (!screenshots.isEmpty()) {
					Screenshot screenshot = (Screenshot)screenshots.get(0);

					sb.append("<img align=\"left\" src=\"");
					sb.append(screenshot.getThumbnailURL());
					sb.append("\" style=\"margin-right: 10px\" />");
				}
			}
		}

		sb.append("<strong>");
		sb.append(pluginPackageName);
		sb.append("</strong> ");
		sb.append(pluginPackageAvailableVersion);

		if (pluginPackage != null) {
			sb.append("</a>");
		}

		if (Validator.isNotNull(pluginPackageShortDescription)) {
			sb.append("<br />");
			sb.append(LanguageUtil.get(pageContext, "id"));
			sb.append(": ");
			sb.append(pluginPackageModuleId);
			sb.append("<br />");
			sb.append(pluginPackageShortDescription);
		}

		row.addText(sb.toString());

		// Trusted

		TextSearchEntry rowTextEntry = new TextSearchEntry(SearchEntry.DEFAULT_ALIGN, SearchEntry.DEFAULT_VALIGN, pluginPackageTags, null, null, null);

		if (PluginPackageUtil.isTrusted(pluginPackageRepositoryURL)) {
			row.addText(LanguageUtil.get(pageContext, "yes"));
		}
		else {
			row.addText(LanguageUtil.get(pageContext, "no"));
		}

		// Tags

		row.addText(rowTextEntry);

		// Installed version

		if (installedPluginPackage != null) {
			row.addText(installedPluginPackage.getVersion());
		}
		else {
			row.addText(StringPool.DASH);
		}

		// Available version

		sb.setIndex(0);

		sb.append(pluginPackageAvailableVersion);
		sb.append("&nbsp;<img align=\"absmiddle\" border=\"0\" src='");
		sb.append(themeDisplay.getPathThemeImages());
		sb.append("/document_library/page.png");
		sb.append("' onmouseover=\"Liferay.Portal.ToolTip.show(this, '");
		sb.append(pluginPackageChangeLog);
		sb.append("')\" />");

		row.addText(sb.toString());

		// Modified date

		row.addText(dateFormatDateTime.format(pluginPackageModifiedDate));

		// Add result row

		resultRows.add(row);
	}
	%>

	<liferay-ui:search-iterator searchContainer="<%= searchContainer %>" />

	<div class="separator"><!-- --></div>

	<div>
		<c:if test="<%= PluginPackageUtil.getLastUpdateDate() != null %>">
			 <%= LanguageUtil.format(pageContext, "list-of-plugins-was-last-refreshed-on-x", dateFormatDateTime.format(PluginPackageUtil.getLastUpdateDate())) %>
		</c:if>

		<aui:button onClick='<%= renderResponse.getNamespace() + "reloadRepositories();" %>' value="refresh" />
	</div>

	<liferay-util:include page="/html/portlet/plugin_installer/repository_report.jsp" />

<%
}
catch (PluginPackageException ppe) {
	if (_log.isWarnEnabled()) {
		_log.warn(ppe.getMessage());
	}
%>

	<div class="portlet-msg-error">
		<liferay-ui:message key="an-error-occurred-while-retrieving-available-plugins" />
	</div>

	<c:if test="<%= windowState.equals(WindowState.MAXIMIZED) %>">
		<aui:script>
			Liferay.Util.focusFormField(document.<portlet:namespace />fm.<portlet:namespace />keywords);
		</aui:script>
	</c:if>

<%
}
%>

<%!
private static Log _log = LogFactoryUtil.getLog("portal-web.docroot.html.portlet.plugin_installer.browse_repository.jsp");
%>