package com.backfire.doudizhu.common;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

public class BitmapDownloadTask extends AsyncTask<String, Void, Bitmap>{
	private int mTag;
	public int getTag() {
		return mTag;
	}

	public void setTag(int mTag) {
		this.mTag = mTag;
	}

	private BitmapDownloadCallback mCallback;

	public BitmapDownloadCallback getCallback() {
		return mCallback;
	}

	public void setCallback(BitmapDownloadCallback mCallback) {
		this.mCallback = mCallback;
	}

	public interface BitmapDownloadCallback {
		void onBitmapDownloadFinished(int tag, Bitmap bitmap);
	}
	
	@Override
	protected Bitmap doInBackground(String... params) {
		Bitmap result = null;
		String url = params[0];
		URL fileUrl = null;
		
		if (url == null)
			return null;
		
		try {
			fileUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		if (fileUrl == null)
			return null;
		
		try {
			HttpURLConnection conn = (HttpURLConnection)fileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			conn.setConnectTimeout(20*1000);//连接超时控制
			InputStream is = conn.getInputStream();
			
			result = BitmapFactory.decodeStream(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return result;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		if (mCallback != null) {
			mCallback.onBitmapDownloadFinished(mTag, result);
		}
	}
}

