package com.backfire.php;

import java.util.ArrayList;

import com.backfire.utils.Log;
import com.backfire.utils.MyAsyncTask;
import com.backfire.utils.MyTaskWrap;

/**
 * @author wf
 *
 */

public class PHPRequestPool {

	public static class RequestListModel
	{
		public PHPCallbackInterface callback = null;
		public PHPConnect theConnect = null;
		public boolean isRequesting = false;
		public MyAsyncTask task = null;
		
		public RequestListModel(PHPCallbackInterface callback, PHPConnect connect) {
			this.callback = callback;
			this.theConnect = connect;
			this.isRequesting = false;
		}
	}

	private static PHPRequestPool phpRequestPool = null;
	private static final int requestPoolMaxSize = 5;
	private ArrayList<RequestListModel> requestPool = null;
	private int count = 0;
	
	private PHPRequestPool()
	{
		//私有，防止外部调用
		if (requestPool == null) 
		{
			requestPool = new ArrayList<RequestListModel>();
		}
	}
	
	public static PHPRequestPool getInstance()
	{
		if (phpRequestPool == null) 
		{
			phpRequestPool = new PHPRequestPool();
		}
		return phpRequestPool;
	}
	/*
	 * 检查两个请求唯一性的方法：判断两个连接的请求方法和请求数据是否一致
	 */
	public PHPConnect AddRequest(PHPCallbackInterface callback, int method, String postData)
	{
		String methodName = String.valueOf(method);
		PHPConnect connect = new PHPConnect(methodName, postData);
		synchronized (requestPool) {
			boolean flag = false;
			for (int i = 0; i < requestPool.size(); i++) {
				RequestListModel r = requestPool.get(i);
				if (r.theConnect.equals(connect)) {
					flag = true;
				}
			}
			if(!flag){
				RequestListModel element = new RequestListModel(callback, connect);
				requestPool.add(element);
			}
		}
		Log.v("Add", "start");
		startTask();
		return connect;
	}
	
	public void RemoveRequest(PHPConnect connect)
	{
		try {
			synchronized (requestPool) 
			{
				for(int i=0; i<requestPool.size(); i++)
				{
					RequestListModel model = requestPool.get(i);
					if (model.theConnect.equals(connect)) //需要对象地址相同
					{
						Log.i("Response", "("+model.theConnect.requestMethod+")finish "+model.theConnect.result.code);
						requestPool.remove(model);
						model.callback.onFinish(model.theConnect.result);
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/*
	 * 原理：每次都取池中的前5个进行处理，
	 * 对这5个进行判断，如果正在执行，则放过
	 * 如果还没开始执行，则启动无痛线程执行
	 * 执行完后才将该任务从池中释放
	 */
	private void startTask()
	{
		for(int i=0; i<requestPoolMaxSize && i<requestPool.size(); i++)
		{
			final RequestListModel model = requestPool.get(i);
			if (!model.isRequesting) {
				model.isRequesting = true;
				model.task = new MyAsyncTask(new MyTaskWrap() {
					
					@Override
					public void onTaskStart() {
						model.theConnect.postRequest();
					}
					
					@Override
					public void onTaskFinish() {
						try {
							RemoveRequest(model.theConnect);
							startTask();
						} catch (Exception e) {
							Log.e(this, e);
						}
					}
				});
				model.task.execute();
			}
		}
	}
	public void resetPool(){
		for(int i= requestPool.size()-1; i>=0; i--)
		{
			RequestListModel model = requestPool.get(i);
			if(model!=null){
				if (!model.isRequesting) {
					requestPool.remove(i);
					model = null;
				}else{
					model.theConnect.abort();
					if(model.task!=null)model.task.cancel(false);
					requestPool.remove(i);
					model = null;
				}
			}
		}
	}
}
