package com.gh.download;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;


public class DataChanger extends Observable {

	private static DataChanger mInstance;

	public static DataChanger getInstance() {
		if(mInstance == null){
			mInstance = new DataChanger();
		}
		return mInstance;
	}

	private final Map<String, DownloadTask> mDownloadingTasks;//当前正在下载的任务队列
	private final Map<String, DownloadEntity> mDownloadEntries;//包含所有下载任务的任务队列

	private DataChanger() {
		mDownloadingTasks = Collections.synchronizedMap(new HashMap<String, DownloadTask>());
		mDownloadEntries = Collections.synchronizedMap(new HashMap<String, DownloadEntity>());
	}

	public Map<String, DownloadTask> getDownloadingTasks() {
		synchronized (mDownloadingTasks) {
			return mDownloadingTasks;
		}
	}

	public Map<String, DownloadEntity> getDownloadEntries() {
		synchronized (mDownloadEntries) {
			return mDownloadEntries;
		}
	}

	public synchronized void notifyDataChanged(DownloadEntity entry) {
		if (entry != null) {
			if (getDownloadEntries().get(entry.getUrl()) != null) {
				getDownloadEntries().put(entry.getUrl(), entry);
				setChanged();		
				notifyObservers(entry);
			}
		}
	}

	public synchronized void pauseDownloadingTasks(String url) {
		DownloadTask downloadTask = getDownloadingTasks().remove(url);
		if (downloadTask != null) {
			downloadTask.pause();
		}
	}

}
