package gr.uoa.di.resourcediscovery;

import gr.uoa.di.resourcediscovery.methods.ResourceDiscoveryMethod;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

import com.thoughtworks.xstream.XStream;

public class MethodProviderFileStorageImpl implements MethodProvider {

	private String pathToFile = null;

	HashMap<URL, ResourceDiscoveryMethod> map = new HashMap<URL, ResourceDiscoveryMethod>();

	public MethodProviderFileStorageImpl() {

	}

	@SuppressWarnings("unchecked")
	public MethodProviderFileStorageImpl(String pathToFile) throws FileNotFoundException {
		XStream xstream = new XStream();
		if(!(new File(pathToFile).exists()))
			map = new  HashMap<URL, ResourceDiscoveryMethod>();
		else
			map = (HashMap<URL, ResourceDiscoveryMethod>) xstream.fromXML(new FileReader(new File(pathToFile)));
		this.pathToFile = pathToFile;
	}

	@Override
	public ResourceDiscoveryMethod getMethod(URL baseUrl) throws MalformedConfigurationException, UnknownMethodException, IOException {
		baseUrl = new URL(Toolkit.getRedirectedUrl(baseUrl.toString(), 500));
		ResourceDiscoveryMethod ret = map.get(new URL(baseUrl.getProtocol()+"://"+baseUrl.getHost()));
		return ret;
	}

	@Override
	public void setMethod(URL baseUrl, ResourceDiscoveryMethod method) {
		map.put(baseUrl, method);
		try {
			store();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getPathToFile() {
		return pathToFile;
	}

	public void setPathToFile(String pathToFile) {
		this.pathToFile = pathToFile;
	}

	public void store() throws IOException {
		XStream xstream = new XStream();
		xstream.toXML(map, new FileWriter(new File(pathToFile)));
	}

}
