package net;

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

import System.CancelableThread;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


public class HttpVideoUploader {
	public static final String TAG = "HttpVideoUploader";
	
	private final Map<Integer, Uploader> mUploads =
		  Collections.synchronizedMap(new HashMap<Integer, Uploader>());
	
	//before: protected final ...
	protected  ConnectivityManager mConnMan = null;
    
	
	private Context ctx;
	
	
	public HttpVideoUploader(Context ctx) {
		this.ctx = ctx;
	}
	
	public Uploader startUpload(int eid) {
		Uploader uploader = new Uploader(eid);
		mUploads.put(eid, uploader);
		uploader.start();
		return uploader;
	}
	
	public void stopUpload(int eid) {
		stopUpload(mUploads.get(eid));
	}
	
	public void stopUpload(Uploader u) {
		if(u != null) {
			u.requestCancelAndWait();
		}
		
	}
	
	public void stopAllUploads() {
        Uploader[] uploadsCopy;
		
		synchronized(mUploads) {
			uploadsCopy = 
			  mUploads.values().toArray(new Uploader[mUploads.size()]);
		}

		for (Uploader u: uploadsCopy)
			stopUpload(u);
	}
	
	public boolean isNetworkAvailable()
	{
		mConnMan = (ConnectivityManager)ctx.getSystemService
		  (Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = mConnMan.getActiveNetworkInfo();
		if (info == null)
			return false;

		return info.isConnected();
	}
	
	
	public static class Uploader extends CancelableThread{
		private int eid;
		ArrayList<String> pathlist;
		private HttpActionManager mManager = new HttpActionManager();
		public Uploader(int eid) {
			pathlist = new ArrayList<String>();
		}
		
		public void addVideoPath(String path) {
			pathlist.add(path);
			Log.i(TAG, "path added: " + path);
		}
		
		public void run(){
			while(true) {
				if(!pathlist.isEmpty()) {
					mManager.addVideo(eid, pathlist.get(0));
					String path_removed = pathlist.remove(0);
					Log.i(TAG, "path removed: " + path_removed);
				}
			}
		}
	}

}

