/*
 * $Id: RequestUtils.java 394468 2006-04-16 12:16:03Z tmjee $
 *
 * Copyright 2006 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.k_int.aggregator.dpp.actions;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import com.k_int.aggregator.datamodel.AggregatorSourceHDO;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class DataSourceInfoAction extends ActionSupport implements ServletRequestAware {
	private static final long serialVersionUID = 1L;
	private static Log log = LogFactory.getLog(DataSourceInfoAction.class);
	private HttpServletRequest request;
	private SessionFactory factory = null;
	private String source_id;
	private String identifier;
	private String title;
	private String search_url = null;
	private String qry;
	private String version;
	private String rows;
	private String start; 
	private AggregatorSourceHDO source = null;
	private String itemsInError; 
	private ArrayList<Object []> invalidItems;
	
	public void setServletRequest(HttpServletRequest request) { this.request = request; }
	public void setSessionFactory(SessionFactory factory)     { this.factory = factory; }
	public AggregatorSourceHDO getSource()                    { return source;          }
	public String getSearchUrl()                              { return search_url;      }
	public void setSearchUrl(String searchUrl)                { this.search_url = searchUrl; }
  
	public String getIdentifier()                { return identifier;            }
	public void setIdentifier(String identifier) { this.identifier = identifier; }  
	public String getTitle()                     { return title;                 }
	public void setTitle(String title)           { this.title = title;           }
	public String getSourceId()                  { return source_id;             }
	public void setSourceId(String source_id)    { this.source_id = source_id;   }
  
	public String getQry() { return qry; }
	public void setQry(String qry) { this.qry = qry; }
  
	public void setVersion(String version) { this.version = version; }
	public String getVersion(String version) { return version; }
  
	public void setStart(String start) { this.start = start; }
	public String getStart() { return start; }

	public void setRows(String rows) { this.rows = rows; }
	public String getRows() { return rows; }

	public void setItemsInError(String itemsInError) {
		this.itemsInError = itemsInError;
	}
	public String getItemsInError() {
		return(itemsInError);
	}
	
	public void setInvalidItems(ArrayList<Object []> invalidItems) {
		this.invalidItems = invalidItems;
	}

	public ArrayList<Object []> getInvalidItems() {
		return(invalidItems);
	}

	@SuppressWarnings("unchecked")
	public String execute() throws Exception {

		Session sess = null;
		try {
			sess = factory.openSession();
			sess.clear();

			Query q = sess.createQuery("Select s from com.k_int.aggregator.datamodel.AggregatorSourceHDO s where s.identifier = ?");
			q.setParameter(0, source_id, Hibernate.STRING);
			source = (AggregatorSourceHDO) q.uniqueResult();

			if ((source != null) && (itemsInError != null) && itemsInError.equals("yes")) {
				Query invalidItemQuery = sess.createSQLQuery("select aggr_resource_fk, substr(title, 1, 250) " +
				                                             "from CG_DM_ITEM, CG_DM_BASE " + 
				                                             "where rules_status in ('EDM_CONVERSION_ERROR', 'VALIDATION_ERROR') and " + 
				                                                   "id = base_id and " + 
						                                           "aggr_resource_fk in (select resource_id " +
						                                                                "from AGGR_RESOURCE_COLLECTIONS_JOIN " +
						                                                                "where collection_id in (select collection_id " +
						                                                                                        "from AGGR_SOURCE_COLLECTIONS_JOIN " +
						                                                                                        "where source_id = ?)) " +
						                                     "limit 0, 100");
				invalidItemQuery.setParameter(0, source.getId());
				setInvalidItems((ArrayList<Object []>)invalidItemQuery.list());
			}
      
		} catch (HibernateException he) {
			log.error("Problem with source info.", he);
		} finally {
			if (sess != null) try { sess.close(); } catch (Exception e) { log.error("Exception thrown closing the session: " + e.getMessage()); e.printStackTrace(); }
		}

		if (invalidItems == null) {
			if (version==null) version = "2.2";
			if (rows==null)    rows    = "10";
			if (start==null)   start   = "0";
	
			if ( title == null ) {
				title = "*";
			}
	    
	
			if (request.getParameter("qry")!=null && request.getParameter("submit")!=null) {
				qry = request.getParameter("qry");
	      
			} else {
				qry = "authority:"+source_id;
	      
				if (title!=null && !title.trim().equals("")) {
					qry+=" AND dc.title:\""+title+"\"";
				}
	              
				if (identifier!=null && !identifier.trim().equals("")) {
					if (!qry.equals(""))
						qry += " AND ";
					qry += " dc.identifier:\""+identifier+"\"";
				}
			}
	    
			log.debug("Contstructed query of :"+qry);
			request.setAttribute("qry",   qry);
			request.setAttribute("ver",   version);
			request.setAttribute("start", start);
			request.setAttribute("rows",  rows);
			request.setAttribute("sort", "timestamp desc");
			request.setAttribute("search_url", search_url);
		}
		return SUCCESS;
	}
}
