package com.qiyou.mb.android.ui.fragments;

import java.io.File;
import java.util.List;

import uk.co.senab.photoview.PhotoViewAttacher;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.ui.MainActivity;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.image.QimageView;
import com.qiyou.mb.android.utils.log.QLog;
 

public class ImageDetailFragment extends QiyouFragment {
//	public static final String TAG ="com.qiyou.ImageDetailFragment";
//	public static final String dTAG ="com.qiyou";

	@Override
	public void setFTag(){
		TAG="com.qiyou.ImageDetailFragment";
	}
	public static String getFTag(){
		return "com.qiyou.ImageDetailFragment";
	}	
	@Override
	public String getCurrentTag(){
		return "com.qiyou.ImageDetailFragment";
	}
	private String mImageUrl;
	private QimageView mImageView;
	private ProgressBar progressBar;
	private PhotoViewAttacher mAttacher;
	ImageDetailFragment fragment ;
    protected MainActivity activity;
	public static ImageDetailFragment newInstance(String imageUrl) {
		final ImageDetailFragment f = new ImageDetailFragment();

		final Bundle args = new Bundle();
		args.putString("url", imageUrl);
		f.setArguments(args);
	 
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mImageUrl = getArguments() != null ? getArguments().getString("url") : null;
		 String fileProtocol ="file://";
    	 String httpProtocol ="http";
    	 if(!mImageUrl.startsWith(fileProtocol) &&!mImageUrl.startsWith(httpProtocol)  ){
    		 mImageUrl =fileProtocol+mImageUrl;
    	 }
		fragment =this;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		final View v = inflater.inflate(R.layout.image_detail_fragment, container, false);
		mImageView = (QimageView) v.findViewById(R.id.image);
		mAttacher = new PhotoViewAttacher(mImageView);
 
		mAttacher.setOnPhotoTapListener(new OnPhotoTapListener() {
			
			@Override
			public void onPhotoTap(View arg0, float arg1, float arg2) {
//				getActivity().finish();
//				FragmentTransaction fragmentTransaction =   getActivity().getSupportFragmentManager().beginTransaction();
//				FragmentTransaction fragmentTransaction =   getChildFragmentManager().beginTransaction();				
//        		fragmentTransaction.remove(fragment);
//        		fragmentTransaction.commitAllowingStateLoss();
				 
			}
		});
		
		progressBar = (ProgressBar) v.findViewById(R.id.loading);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
//		 activity = (MainActivity)getActivity();	   
//		 activity.app.currentActiveFragment =TAG; 
		
//		 DisplayImageOptions dio =new DisplayImageOptions();
//		 
//		 ImageLoader.getInstance().displayImage(mImageUrl, mImageView, null);
 		 
//			  ImageLoader.getInstance().displayImage(mImageUrl, mImageView, new SimpleImageLoadingListener() 
			
			 ImageLoader.getInstance().displayImage(mImageUrl, mImageView, new SimpleImageLoadingListener() {
		//			@Override
		//			public void onLoadingStarted(String imageUri, View view) {
		//				progressBar.setVisibility(View.VISIBLE);
		//			}
					 boolean cacheFound;  
					  
		             @Override  
		             public void onLoadingStarted(String imageUri, View view) {
		//            	 QLog.getLogger().d(dTAG,TAG+" begin to load image of :" +imageUri );
		            	
		            	 QLog.getLogger().d(dTAG,TAG+" begin to load image of :" +imageUri );
		            	 
		            	 progressBar.setVisibility(View.VISIBLE);
		                 List<String> memCache = MemoryCacheUtils  
		                         .findCacheKeysForImageUri(imageUri, ImageLoader  
		                                 .getInstance().getMemoryCache());  
		                 cacheFound = !memCache.isEmpty();  
		                 if (!cacheFound) {  
		                     File discCache = DiskCacheUtils.findInCache(  
		                             imageUri, ImageLoader.getInstance()  
		                                     .getDiskCache());  
		                     if (discCache != null) {  
		                         cacheFound = discCache.exists();  
		                     }  
		                 }  
		                QLog.getLogger().d(dTAG, "Cache exits?"+cacheFound);
		             }  
		//
		             @Override  
		             public void onLoadingComplete(String imageUri, View view,  
		                     Bitmap loadedImage) {  
		            	 progressBar.setVisibility(View.GONE);  
		            	 try{
		            		  QLog.getLogger().d(dTAG, " loading complete");
		            		 mAttacher.update();
		            	 }catch (Exception e){
		            		 Utils.logStackTrace(e, dTAG);
		            	 }
		 				 
		                 if (cacheFound) {  
		                    /* MemoryCacheUtils.removeFromCache(imageUri,  
		                             ImageLoader.getInstance().getMemoryCache());  
		                     DiskCacheUtils.removeFromCache(imageUri, ImageLoader  
		                             .getInstance().getDiskCache());   */
		                     
		 
		                 }
		                 
		             }
		             
					@Override
					public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
						String message = null;
						switch (failReason.getType()) {
						case IO_ERROR:
							message = "下载错误，图片不存在";
							break;
						case DECODING_ERROR:
							message = "图片无法显示";
							break;
						case NETWORK_DENIED:
							message = "网络有问题，无法下载";
							break;
						case OUT_OF_MEMORY:
							message = "内存不足,图片太大无法显示";
		//					ImageLoader.getInstance().destroy();
		//					activity.app.initialImageLoader();
							ImageLoader.getInstance().clearMemoryCache();
		//					ImageLoader.getInstance().getMemoryCache().clear();
							ImageLoader.getInstance().clearDiskCache();
							mAttacher.cleanup();
							break;
						case UNKNOWN:
							message = "未知的错误";
							break;
						}
		//				Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
						showNotes(message); 
						progressBar.setVisibility(View.GONE);
					}
		
		//			@Override
		//			public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
		//				progressBar.setVisibility(View.GONE);
		//				mAttacher.update();
		//			}
				});

		
	}
	
	@Override
	public void onResume() {
		super.onResume();			 
//	   	activity.app.currentActiveFragment =TAG;
		
		 
	}
	
	
	@Override
	public void onDestroy(){ 
		QLog.getLogger().d(dTAG,TAG+ "    Fragment onDestory....");
		
		BitmapDrawable drawable =mImageView==null?null: (BitmapDrawable)mImageView.getDrawable();
		
		if(drawable!=null){
			Bitmap bmp = drawable.getBitmap();
			if (null != bmp && !bmp.isRecycled()){
			 bmp.recycle();
	//		 bmp = null;
			 mAttacher.cleanup();
//			 mAttacher=null;
//			 System.gc();
			 QLog.getLogger().d(dTAG,TAG+ " Image recycled when fragment destory.");
			}
		}
		super.onDestroy();
	}
	@Override
	public boolean isShowBottomTabs() {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public void setTabOnFiling() {
		// TODO Auto-generated method stub
		
	}
	
	/* class MyImageView extends ImageView {  
		  
	    public MyImageView (Context context, AttributeSet attrs) {  
	        super(context, attrs);  
	    }  
	  
	    @Override  
	    protected void onDraw(Canvas canvas) {  
	        try {  
	            super.onDraw(canvas);  
	        } catch (Exception e) {  
	        	QLog.getLogger().d(dTAG,"trying to use a recycled bitmap");  
	        }  
	    }
	 }*/
}
