<%--
  - export-ojs.jsp
  -
  - Version: $Revision: 1.24 $
  -
  - Date: $Date: 2006/09/08 15:43:45 $
  -
  - Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
  - Institute of Technology.  All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are
  - met:
  -
  - - Redistributions of source code must retain the above copyright
  - notice, this list of conditions and the following disclaimer.
  -
  - - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  -
  - - Neither the name of the Hewlett-Packard Company nor the name of the
  - Massachusetts Institute of Technology nor the names of their
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  -
  - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  - HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  - OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  - USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  - DAMAGE.
  --%>

<%--
  - Community home JSP
  -
  - Attributes required:
  -    community             - Community to render home page for
  -    collections           - array of Collections in this community
  --%>

<%@ page contentType="text/xml;charset=UTF-8" %>


<%@ page import="org.dspace.app.webui.util.UIUtil" %>
<%@ page import="org.dspace.content.Bitstream" %>
<%@ page import="org.dspace.content.Community" %>
<%@ page import="org.dspace.content.Collection" %>
<%@ page import="org.dspace.content.Bundle" %>
<%@ page import="org.dspace.content.Item" %>
<%@ page import="org.dspace.content.ItemIterator" %>
<%@ page import="org.dspace.content.DCValue" %>
<%@ page import="org.dspace.content.DCPersonName" %>
<%@ page import="org.dspace.core.Constants" %>
<%@ page import="org.dspace.core.Context" %>
<%@ page import="org.dspace.core.ConfigurationManager" %>
<%@ page import="java.util.regex.Matcher" %>
<%@ page import="java.util.regex.Pattern" %>
<%@ page import="org.dspace.app.webui.util.Base64Coder" %>
<%@ page import="org.dspace.app.webui.util.SortUtil"%>

<%@ page import="org.dspace.browse.BrowseInfo"%>
<%@ page import="org.dspace.browse.BrowseIndex"%>
<%@ page import="org.dspace.browse.BrowseEngine"%>
<%@ page import="org.dspace.browse.BrowserScope"%>
<%@ page import="org.dspace.search.QueryResults" %>
<%@ page import="org.apache.commons.lang.StringEscapeUtils" %>
<%@ page import="org.dspace.sort.SortOption" %>
<%@ page import="org.dspace.app.webui.util.SortUtil"%>

<%!

	String cleanTags(String tempValue)
	{
				tempValue = tempValue.replaceAll("&","&amp;");
				tempValue = tempValue.replaceAll("<","&lt;");
				tempValue = tempValue.replaceAll(">","&gt;");
				tempValue = tempValue.replaceAll("\"","");
				
				return tempValue;
	}

	String printTag(String name, String value, boolean required)
	{
		if (value != null)
		{
			if (name.equals("firstname") || name.equals("surname"))
			{
					if (value.equals("")) value = " ";
			}
			
			return "<" + name + ">" + cleanTags(value) + "</" + name + ">";
		} 
		else if (required) 
		{
			return "<" + name + "> </" + name + ">";
		}
		
		return "";
	}

	String printDCTag(String name, DCValue[] values, boolean multiple)
	{
		String acum = "";
		
		// Only show 3 values for tag
		if (multiple)
		{
			
			for (int l=0;l<values.length && l<3;l++)
			{
				if (name.equals("abstract") && values[l].language != null)
				{
					String lang = values[l].language;
					if (lang.equals("en"))				lang = "en_US";
					else if (lang.equals("es"))		lang = "es_ES";
					else if (lang.equals("ca"))		lang = "ca_ES";
										
					acum = acum + "<" + name + " locale=\"" + lang + "\" >" + cleanTags(values[l].value) + "</" + name + ">";	
				}
				else
				{
					acum = acum + "<" + name + ">" + cleanTags(values[l].value) + "</" + name + ">";
				}
			} 
		}
		else
		{
			if (values.length > 0)
			{
				if (name.equals("pages"))
				{
					boolean found = false;
					for (int l=0;l<values.length && !found;l++)
					{
						if (values[l].value.indexOf("bytes") < 0)
						{
							Pattern p3 = Pattern.compile("([0-9]+)-([0-9]+)");
		        	Matcher m3 = p3.matcher(values[l].value);
		        	
		        	if (m3.find())
		        	{
		        		String result = m3.group();
								found = true;
								acum = acum + "<" + name + ">" + cleanTags(result) + "</" + name + ">";
							}
							else
							{
									Pattern p4 = Pattern.compile("([0-9]+)");
									Matcher m4 = p4.matcher(values[l].value);
									if (m4.find())
									{
											String result = m4.group();
											found = true;
											acum = acum + "<" + name + ">" + cleanTags(result) + "</" + name + ">";
									}
							}	
						}
					}
				}
				else if (name.equals("date_published"))
		    {
				    Pattern p1 = Pattern.compile("[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]");
		        Matcher m1 = p1.matcher(values[0].value);
		        if (m1.find())
		        {
		         acum = "<" + name + ">" + m1.group() + "</" + name + ">";
		        }
			      else
			      {	 
					   //   Pattern p2 = Pattern.compile("[0-9][0-9][0-9][0-9]-[0-9][0-9]");
					   //   Matcher m2 = p2.matcher(values[0].value);
					   //   if (m2.find())
					   //   {
					   //      acum = "<" + name + ">" + m2.group() + "-01</" + name + ">";
					   //   }   
					   // 	else
					   // 	{
							      Pattern p3 = Pattern.compile("[0-9][0-9][0-9][0-9]");
							      Matcher m3 = p3.matcher(values[0].value);
							      if (m3.find())
							      {
							         acum = "<" + name + ">" + m3.group() + "</" + name + ">";
							      } 
					    //  }
			      }  			      
		    }
				else
				{
					acum = "<" + name + ">" + values[0].value + "</" + name + ">";
				}		
			}
		}
		
		return acum;
	}

%>

<%
    // Retrieve attributes
    Community community = (Community) request.getAttribute( "community" );
    Collection[] collections =
        (Collection[]) request.getAttribute("collections");

    // Put the metadata values into guaranteed non-null variables
    String name = community.getMetadata("name");
%>
	<!DOCTYPE issues SYSTEM "https://upcommons.upc.edu/revistes/native.dtd">
	<issues>
<%
    for (int i = 0; i < collections.length; i++)
    {
    	Pattern p;
    	Matcher m;
    	
    	String title = collections[i].getMetadata("name");
    	String description  = (String) request.getParameter("description_" + collections[i].getID());
  		if (description.equals("")) description = null;
    	String volume = (String) request.getParameter("volume_" + collections[i].getID());
    	if (volume.equals("")) volume = null;
    	String number = (String) request.getParameter("number_" + collections[i].getID());
    	if (number.equals("")) number = null;
    	String year = (String) request.getParameter("year_" + collections[i].getID());
    	if (year.equals("")) year = null;
    	String caption = (String) request.getParameter("caption_" + collections[i].getID());
    	if (caption.equals("")) caption = " ";
    	String date_published = null;
    	
    	//Generate title
    	if (volume != null && number != null)
    			title = "Vol.: " + volume + " Núm.: " + number;
    	if (volume == null && number != null)
    			title = "Núm.: " + number;
    	if (volume != null && number == null)
    			title = "Vol.: " + volume;
    	if (volume == null && number == null)	
    			title = year;	
    	
    	if (caption != null) 
    			title = title + " " + caption;		
%>

		<issue identification="title" published="true" current="false">
			<%=printTag("title",title,true)%>
			<%=printTag("description",description,false)%>
			<%=printTag("volume",volume,false)%>
		  <%=printTag("number",number,false)%>
			<%=printTag("year",year,false)%>
			<%
			Bitstream logo = collections[i].getLogo();
			if (logo != null)
			{
			%>
			<cover>
				<%=printTag("caption","",true)%>
				<%if (logo != null){%>
				<image>
					<href src="http://upcommons.upc.edu/revistes/retrieve/<%= logo.getID() %>" mime_type="<%=logo.getFormat().getMIMEType()%>" />
				</image>
				<%}%>
			</cover>
			<%
			}
			%>
			<%=printTag("date_published",date_published,false)%>
			<open_access />
			
			
		<%//////SECTION///////%>
			<section>
				<title>Articles</title>
				<abbrev>ART</abbrev>
<%
			// Get the items array
			Context context;
			context = UIUtil.obtainContext(request);

			String indexOption = ConfigurationManager.getProperty("webui.collection-home.order.index");
			int sortByOption = ConfigurationManager.getIntProperty("webui.collection-home.order.sortby");
			String directionOption = ConfigurationManager.getProperty("webui.collection-home.order.direction");
			int resultPerPageOption = ConfigurationManager.getIntProperty("webui.collection-home.order.resultperpage");
			if (indexOption == null || indexOption.equals("")) 		indexOption = "title";
			if (sortByOption == -1)						sortByOption = 3;
			if (directionOption == null || directionOption.equals("")) 	directionOption = "DESC";

			// set up a BrowseScope and start loading the values into it
			BrowserScope scope = new BrowserScope(context);
			BrowseIndex bi = BrowseIndex.getBrowseIndex(indexOption);
			scope.setBrowseIndex(bi);
			scope.setOrder(directionOption);
			//scope.setFilterValue(value);
			//scope.setFilterValueLang(valueLang);
			//scope.setJumpToItem(focus);
			//scope.setJumpToValue(valueFocus);
			//scope.setJumpToValueLang(valueFocusLang);
			//scope.setStartsWith(startsWith);
			scope.setOffset(0);
			scope.setResultsPerPage(resultPerPageOption);
			scope.setSortBy(sortByOption); // date accesioned?
			//scope.setBrowseLevel(level);
			scope.setEtAl(-1); //sense limit authors
			scope.setBrowseContainer(collections[i]);

			BrowseEngine be = new BrowseEngine(context);
			BrowseInfo binfo = be.browse(scope);
		   	BrowseIndex bix = binfo.getBrowseIndex();

			Item[] items = SortUtil.SortItems(context,binfo.getItemResults(context),collections[i]);
			
			for(int ii=0;ii<items.length;ii++)
    	{
    			Item item = items[ii];
    			String language = null;
    			
    			DCValue[] lang = item.getDC("language","iso",Item.ANY);
    			if (lang[0].value.equals("ca")) language = "cat";
    			if (lang[0].value.equals("es")) language = "spa";
    			if (lang[0].value.equals("en")) language = "eng";
    			if (lang[0].value.equals("fr")) language = "fra";
    			if (lang[0].value.equals("it")) language = "ita";
    		
    			// FIXME: cal seleccionar el valor de language, amb tres lletres, iso...
%>			
				<article language="<%=language%>">
					<%=printDCTag("title",item.getDC("title",null,Item.ANY),true)%>
					<%=printDCTag("abstract",item.getDC("description","abstract",Item.ANY),true)%>
					<%=printDCTag("date_published",item.getDC("date","issued",Item.ANY),false)%>
									
					<%
					//Subjects / indexing...
					//DCValue[] pclau = item.getDC("subject","other",Item.ANY);
					//DCValue[] mat = item.getDC("subject","none",Item.ANY);
					//if (pclau.length > 0 || mat.length > 0)
					//{
					//	String subject = "";
					//	String subject_class = "";
					//	for(int k=0;k<pclau.length;k++)
					//	{
					//			subject = (k==0)? pclau[k].value:subject + ", " + pclau[k].value; 
					//	}
					//	for(int k=0;k<mat.length;k++)
					//	{
					//			subject_class = (k==0)? mat[k].value:subject_class + ", " + mat[k].value; 
					//	}
					
					//<indexing>
					//	printTag("subject_class",subject_class,false)
					//	printTag("subject",subject,false)
					//</indexing>  
					
					
					//}
					%>
					
					<%
					//Authors
					DCValue authors[] = item.getDC("contributor","author",Item.ANY);
					for(int k=0;k<authors.length;k++)
					{
						DCPersonName PNAuthor = new DCPersonName(authors[k].value); 
					%>
						<author primary_contact="<%=(k == 0)%>">
						<%=printTag("firstname",PNAuthor.getFirstNames(),true)%>
						<%=printTag("lastname",PNAuthor.getLastName(),true)%>
						<%=printTag("email"," ",true)%>
						</author>
					<%
					}
					// FIXME: Puede no existir ningun autor, esto petaria, es necesario
					// definir uno para cumplir el DTD
					if (authors.length == 0)
					{
					%>
						<author primary_contact="true">
						<%=printTag("firstname"," ",true)%>
						<%=printTag("lastname"," ",true)%>
						<%=printTag("email"," ",true)%>
						</author>					
					<%
					}
					// publisher, se puede considerar autor
					%>
					<%//printDCTag("pages",item.getDC("format","extent",Item.ANY),false)%>
					
					<%
					
					
					//Files
					/*
					String label = "";					
					String href = "";
					
					// Init values
					Bundle[] bundles = item.getBundles("ORIGINAL");

		        	if (bundles.length == 0)
		        	{
		        		//FIXME: Exception!!!!!!!
		        	}
	        	
        			boolean html = false;
        			String handle = item.getHandle();
        			Bitstream primaryBitstream = null;
							boolean multiFile = false;
										
	        		//Bundle[] allBundles = item.getBundles();
	
	        		for (int h = 0, filecount = 0; (h < bundles.length)
	                    	&& !multiFile; h++)
	        		{
	        			filecount += bundles[h].getBitstreams().length;
	        			multiFile = (filecount > 1);
	        		}
	
	        		// check if primary bitstream is html
	        		if (bundles[0] != null)
	        		{
	        			Bitstream[] bits = bundles[0].getBitstreams();
	
	        			for (int h = 0; (h < bits.length) && !html; h++)
	        			{
	        				if (bits[h].getID() == bundles[0].getPrimaryBitstreamID())
	        				{
	        					html = bits[h].getFormat().getMIMEType().equals(
	        							"text/html");
	        					primaryBitstream = bits[h];
	        				}
	        			}
	        		}
	
	            	// if primary bitstream is html, display a link for only that one to
	            	// HTMLServlet
	            	
	           
	            	
	            	if (html)
	            	{
	            		if (multiFile)
	            		{
	            			label = primaryBitstream.getDescription();
	            			label = (label != null) ? label : "Text";
	            		}
	            		else
	            		{
	            			label = "Text Complet";
	            		}
	                  
						href = ConfigurationManager.getProperty("dspace.url") + request.getContextPath() + "/html/" +  handle + "/"
		            			+ UIUtil.encodeBitstreamName(primaryBitstream.getName(), Constants.DEFAULT_ENCODING);
	            	

	            	
	            	}	
	            	else
	            	{
	            		String mime_type = null;
	            		label = "";
	            		href = "";
	            		
	            		for (int h = 0; h < bundles.length; h++)
	            		{
	            			Bitstream[] bitstreams = bundles[h].getBitstreams();
	
	            			for (int k = 0; k < bitstreams.length; k++)
	            			{
	            				// Skip internal types
	            				if (!bitstreams[k].getFormat().isInternal())
	            				{
	            					if (multiFile)
	            					{
	            						label = bitstreams[k].getDescription();
	            						label = (label != null) ? label : "Text";
	            					}
	            			   		else
				            		{
				            			label = "Text Complet";
				            		}

	            					if ((handle != null)
	            							&& (bitstreams[k].getSequenceID() > 0))
	            					{
	            						href = ConfigurationManager.getProperty("dspace.url") + request.getContextPath() + "/bitstream/"
	                                        	+ item.getHandle() + "/"
	                                        	+ bitstreams[k].getSequenceID() + "/";
	            					}
	            					else
	            					{
	            						href = ConfigurationManager.getProperty("dspace.url") + request.getContextPath() + "/retrieve/"
	                                        	+ bitstreams[k].getID() + "/";
	            					}
	
	            					href = href
	                                    	+ UIUtil.encodeBitstreamName(bitstreams[k]
	                                            .getName(),
	                                            Constants.DEFAULT_ENCODING);
	                                            
	                                mime_type = bitstreams[k].getFormat().getMIMEType();            
								*/
								
					%>			
						
					<%			
								String label = "Text complet";
								String mime_type = "text/html";
								String href = "http://hdl.handle.net/"
	                                        	+ item.getHandle();
					
					
								//construim el html, redirect.html
								String content_redirect = "<br/><br/>Per accedir al text complet de l'article, si us plau seguiu el" 
										+	" seg&uuml;ent enlla&ccedil;:" 
										+	" <br/>Para acceder al texto completo del art&iacute;culo, por favor siga" 
										+	" el siguiente enlace:" 
										+	" <br/>To access the full text article, please click the link below:" 
										+	" <br/><br/><a" 
										+	" href=\"" + href + "\" >" + href + "</a>";
					
					
					%>
					<htmlgalley>
						<label><%=label%></label>
      			<file>
      				<embed filename="redirect.html" encoding="base64" 
									mime_type="text/html"><%=Base64Coder.encodeString(content_redirect)%></embed>
      				</file>
					</htmlgalley>

	            	<%
	            	/*
	         					}
								   	
							}
						}
					}
					*/
					%>
					
					<%
					// Suplemental file
					// Dades extres???
					%>
					
				</article>
<%
			}
%>
			</section>
		</issue>
<%
	};
%>
	</issues>
