/*
* This file is part of 3DzzD http://dzzd.net/.
*
* Released under LGPL
*
* 3DzzD is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 3DzzD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 3DzzD.  If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2005 - 2009 Bruno Augier
*/

package net.dzzd.utils.io;

import net.dzzd.access.*;
import net.dzzd.utils.Log;

import java.io.*;

public class IOManagerAsynch implements Runnable
{
	private volatile byte[] data;
	private volatile String dataSource;
	private volatile boolean loading;
	private volatile boolean loadingError;
	private volatile Thread thread;
	
	public IOManagerAsynch()
	{
		
	}
	
	public IOManagerAsynch downloadData(String dataSource) throws IOException
	{
		if(this.isLoading())
			throw new IOException("IOManagerAsynch is already loading another ressource");
		this.dataSource=dataSource;
		this.data=null;
		this.loadingError=false;
		this.loading=true;	
		this.thread=new Thread(this,"3DZZD ASYNCH DATA LOADER");		
		this.thread.start();
		return this;
	}
	
	public void run()
	{
		try
		{
			this.data = IOManager.downloadData(this.dataSource);
		}
		catch(IOException ioe)
		{
			Log.log(ioe);
			this.loadingError=true;
		}
		this.loading=false;
		this.thread=null;
	}
	
	public String getDataSource()
	{
		return this.dataSource;
	}
	
	public boolean isLoading()
	{
		return (this.thread != null || this.loading );
	}
	
	public boolean isLoadingError()
	{
		return this.loadingError;
	}	
	
	public byte[] getData()
	{
		return this.data;
	}
}