package uwl.rss.provider;

import java.io.File;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.sap.tc.logging.Category;
import com.sap.tc.logging.Location;
import com.sap.tc.logging.Severity;
import com.sun.syndication.feed.synd.SyndFeed;

/**
 * @author Sumit Gogia,SAP
 *
 */
public class RssItemProvider {

	private static final Location loc = Location.getLocation(RssItemProvider.class);

	/*
	 * location of the xml file in which we maintain the list of
	 * RSS Feed URLs that each user has subscribed to.
	 * Currently we depend on the RssRegistrationService to set this
	 * path during its init method call.
	 */
	public static String pathXmlStore = null;	
	private static long lastReadTimestamp = -1;
	
	/*
	 * Rss Subscription information (RssBeans) stored here.
	 * key=userId
	 * value=arraylist of RssBeans
	 */ 
	private Hashtable userRssSubcriptions = null;
	
	/*
	 * default RSS subscription for a user if the user has no 
	 * subscriptions maintained. May be null.
	 */
	private String defaultUrl = null;
	private String defaultTitle = null;
	
	public RssItemProvider() {
		initialize();
	}
	
	/*
	 * Initialization of the Item Provider.
	 * Read the xmlStore for users' RSS Subscriptions
	 */
	public synchronized void initialize() {
		if(pathXmlStore == null) {
			Category.APPLICATIONS.log(Severity.FATAL,
										loc,
										(Object)"RssItemProvider()",
										new Object[]{this},
										"Path to XML Store containing User's RSS Subscriptions not set!");
			return;
		}
		
		File file = new File(pathXmlStore);
		long timestamp = file.lastModified();
		if(timestamp == lastReadTimestamp) return;		
		lastReadTimestamp = timestamp;
				
		userRssSubcriptions = new Hashtable();
		try {
			SAXBuilder builder = new SAXBuilder();
			builder.setValidation(false);
			builder.setIgnoringElementContentWhitespace(true);
			Document doc = builder.build(pathXmlStore);
			Element defaultRssFeed = doc.getRootElement().getChild("default");
			if(defaultRssFeed != null) {
				defaultUrl = defaultRssFeed.getAttributeValue("url");
				defaultTitle = defaultRssFeed.getAttributeValue("title");
			}

			List users = doc.getRootElement().getChildren("user");
			Iterator it = users.iterator();
			while (it.hasNext()) {
				Element user = (Element) it.next();
				String userId = user.getAttributeValue("id");
				List feeds = user.getChildren("feed");
				
				//nothing to add for the user.
				if(feeds.isEmpty()) continue;
				
				ArrayList userRssBeans = new ArrayList();
				Iterator feedIt = feeds.iterator();
				while (feedIt.hasNext()) {
					Element feed = (Element) feedIt.next();
					String rssFeedurl = feed.getAttributeValue("url");
					String rssFeedTitle = feed.getAttributeValue("title");
					boolean bdisabled = Boolean.valueOf(feed.getAttributeValue("disabled")).booleanValue();
					RssBean rssBean = new RssBean(rssFeedurl,rssFeedTitle,bdisabled);
					userRssBeans.add(rssBean);
				}
				userRssSubcriptions.put(userId, userRssBeans);
			}
		}
		catch(Exception e) {
			Category.APPLICATIONS.logThrowable(Severity.FATAL,
												loc,
												(Object)"initialize()",
												new Object[]{this},
												"Error in Initialization of the RssItemProvider",
												e);
		}
	}

	private RssBean[] getRssBeans(String userId) {
		//incase the xmlStore for subscriptions was updated.
		initialize();
		
		RssBean[] beans = null;
		if(userRssSubcriptions != null) {
			ArrayList rssBeans = (ArrayList)userRssSubcriptions.get(userId);
			if( (rssBeans == null) || (rssBeans.isEmpty()) ) {
				//if we have a default feed information, return that.
				if( (defaultUrl != null) && (defaultTitle != null) ) {
					RssBean defaultBean = new RssBean(defaultUrl, defaultTitle, false);
					beans = new RssBean[]{defaultBean};
				}
			}
			else beans = (RssBean[])rssBeans.toArray(new RssBean[]{});
		}
		
		return beans;
	}

	public Hashtable getRssFeeds(String userId){		
		RssBean[] rssBeans = getRssBeans(userId);
		Hashtable feeds = null;
		if(rssBeans != null) {
			feeds = new Hashtable(rssBeans.length);
			for (int i = 0; i < rssBeans.length; i++) {
				if(!rssBeans[i].isDisabled()) {
					SyndFeed feed = rssBeans[i].getRssFeed();
					if(feed != null) feeds.put(rssBeans[i].getTitle(), feed);
				}
			}
		}
		return feeds;
	}
}
