/*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). 
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: 
*
*/

package com.nokia.carbide.cpp.internal.news.reader.gen.FeedCache;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;

import com.nokia.carbide.cpp.internal.news.reader.gen.FeedCache.impl.FeedCacheFactoryImpl;
import com.nokia.carbide.cpp.internal.news.reader.gen.FeedCache.util.FeedCacheResourceFactoryImpl;

/**
 * A class for loading/saving cached feed information from/to an XML file.
 *
 */
public class FeedCacheLoader {

	/**
	 * Load cached feed information from a file.
	 * @param url - Full path to the file
	 * @return a FeedCacheType object with cached feed information
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	public static FeedCacheType loadFeedCache(URL url)
		throws URISyntaxException, IOException  {
		if (url == null)
			return null;

		URI uri = URI.createURI(url.toString());
		FeedCacheResourceFactoryImpl factory = new FeedCacheResourceFactoryImpl();
		Resource r = factory.createResource(uri);
		r.load(null);
		EList<EObject> contents = r.getContents();
		DocumentRoot root = (DocumentRoot)contents.get(0);
		FeedCacheType feedCache = root.getFeedCache();
		return feedCache;
	}

	/**
	 * Save cached feed information to a file.
	 * @param feedCache - the cached feed information to be saved
	 * @param url - Full path to the file
	 * @return true on success
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	public static boolean SaveFeedCache(FeedCacheType feedCache, URL url)
		throws URISyntaxException, IOException {
		if (url == null)
			return false;

		URI uri = URI.createURI(url.toString());
		FeedCacheResourceFactoryImpl rsrcFactory = new FeedCacheResourceFactoryImpl();
		Resource r = rsrcFactory.createResource(uri);
		EList<EObject> contents = r.getContents();
		FeedCacheFactoryImpl factory = new FeedCacheFactoryImpl();
		DocumentRoot root = factory.createDocumentRoot();
		root.setFeedCache(feedCache);
		contents.add(root);
		r.save(null);
		return true;		
	}

}
