package com.gh.common.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.support.v4.util.ArrayMap;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.gh.common.view.CircleImageView;
import com.gh.gamecenter.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.lang.ref.WeakReference;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ImageUtils {
    private static ImageUtils singleton;
    private static ImageLoader imageLoader;
    private static DisplayImageOptions options;
    private ArrayMap<String, WeakReference<Bitmap>> imageCache = new ArrayMap<String, WeakReference<Bitmap>>();

	ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);

	public static ImageUtils getInstance(Context context) {
		if (singleton == null) {
			synchronized (ImageUtils.class) {
				if (singleton == null) {
					singleton = new ImageUtils(context.getApplicationContext(),
							(int) Runtime.getRuntime().maxMemory() / 10);
					return singleton;
				}

			}
		}
		return singleton;
	}

    private ImageUtils(Context context, int size) {

		options = new DisplayImageOptions.Builder().cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.bitmapConfig(Bitmap.Config.RGB_565)
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
				// .showImageOnLoading(R.drawable.ocupy)
				// .showImageForEmptyUri(R.drawable.ocupy)
				// .showImageOnFail(R.drawable.ocupy)
				.build();

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).writeDebugLogs()
                .memoryCacheExtraOptions(480, 800)
                .build();

		ImageLoader.getInstance().init(config);
		imageLoader = ImageLoader.getInstance();
	}

	public void displayFile(String url, ImageView imageView) {
		imageLoader.displayImage(url, imageView, options,
				new ImageLoadingListener() {

					@Override
					public void onLoadingCancelled(String arg0, View arg1) {

					}

					@Override
					public void onLoadingComplete(String arg0, View view,
							Bitmap arg2) {
						AlphaAnimation animation = new AlphaAnimation(0f, 1f);
						animation.setDuration(500);
						view.startAnimation(animation);
					}

					@Override
					public void onLoadingFailed(String arg0, View arg1,
							FailReason arg2) {

					}

					@Override
					public void onLoadingStarted(String arg0, View arg1) {

					}

				});
	}
	//增加一个上下文环境，图片宽度设最大(paddSize为左右边距大小)，高度自适应
	public void display(String url, ImageView imageView, int drawable, Context context, int paddingSize) {
		display(url, imageView, drawable, ScaleType.FIT_XY, null, context, paddingSize);
	}

	public void display(String url, ImageView imageView, int drawable) {
		display(url, imageView, drawable, ScaleType.FIT_XY, null);
	}

	public void display(final String url, final ImageView imageView,
			final int drawable, final ScaleType scaleType,
			final OnLoadingCompleteListener listener) {
		imageLoader.displayImage(url, imageView, options,
				new ImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						if (imageView instanceof CircleImageView) {
							imageView.setScaleType(ScaleType.CENTER_CROP);
						} else {
							imageView.setScaleType(scaleType);
						}
						if (listener != null) {
							listener.onLoadingComplete();
						}
					}

					@Override
					public void onLoadingStarted(String imageUri, View view) {
						if (imageView instanceof CircleImageView) {
							imageView.setScaleType(ScaleType.CENTER_CROP);
						} else {
							imageView.setScaleType(ScaleType.CENTER);
						}
						if (drawable != -1) {
							imageView.setImageResource(drawable);
						}
					}

					@Override
					public void onLoadingCancelled(String imageUri, View view) {

					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason reason) {

					}
				});
	}

	public void display(final String url, final ImageView imageView,
						final int drawable, final ScaleType scaleType,
						final OnLoadingCompleteListener listener, final Context context, final int paddSize) {
		imageLoader.displayImage(url, imageView, options,
				new ImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view,
												  Bitmap loadedImage) {
						int width = loadedImage.getWidth();
						int height = loadedImage.getHeight();
						int widthPixels = context.getResources().getDisplayMetrics().widthPixels;
						widthPixels = widthPixels - DisplayUtils.dip2px(context,paddSize);
						float index = (float) height / (float) width;
						int newHeight = (int)(index * widthPixels);

						ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
						if (layoutParams != null){
							layoutParams.height = newHeight;
							layoutParams.width = widthPixels;
							imageView.setLayoutParams(layoutParams);
						}

						if (imageView instanceof CircleImageView) {
							imageView.setScaleType(ScaleType.CENTER_CROP);
						} else {
							imageView.setScaleType(scaleType);
						}
						if (listener != null) {
							listener.onLoadingComplete();
						}
					}

					@Override
					public void onLoadingStarted(String imageUri, View view) {
						imageView.setScaleType(ScaleType.CENTER);
						if (drawable != -1) {
							imageView.setImageResource(drawable);
						}
					}

					@Override
					public void onLoadingCancelled(String imageUri, View view) {

					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
												FailReason reason) {

					}
				});
	}

    public void display(final String url, final ImageView imageView,
                        final int drawable, final ScaleType scaleType,
                        final OnLoadingCompleteListener listener, final int i) {
        imageLoader.displayImage(url, imageView, options,
                new ImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view,
                                                  Bitmap loadedImage) {
                        WeakReference<Bitmap> bitmapWeakReference = imageCache.get(imageUri);
                        try {
                            if (bitmapWeakReference!=null){
                                Bitmap bitmap = bitmapWeakReference.get();
                                imageView.setImageBitmap(bitmap);
                            }else {
                                Matrix m = new Matrix();
                                m.setRotate(i, (float) loadedImage.getWidth() / 2, (float) loadedImage.getHeight() / 2);
                                Bitmap bm1 = Bitmap.createBitmap(loadedImage, 0, 0, loadedImage.getWidth(), loadedImage.getHeight(), m, true);
                                imageView.setImageBitmap(bm1);
                                WeakReference<Bitmap> weakBM = new WeakReference<Bitmap>(bm1);
                                imageCache.put(imageUri, weakBM);
                            }

                        } catch (OutOfMemoryError ex) {
							Utils.log("Bitmap:::内存溢出");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (imageView instanceof CircleImageView) {
                            imageView.setScaleType(ScaleType.CENTER_CROP);
                        } else {
                            imageView.setScaleType(scaleType);
                        }
                        if (listener != null) {
                            listener.onLoadingComplete();
                        }
                    }

                    @Override
                    public void onLoadingStarted(String imageUri, View view) {
                        imageView.setScaleType(ScaleType.CENTER);
                        if (drawable != -1) {
                            imageView.setImageResource(drawable);
                        }
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view,
                                                FailReason reason) {

                    }
                });
    }

	//获取图片BitMap
	public void  loadBitmap(String url, ImageLoadingListener listener){
		imageLoader.loadImage(url, listener);
	}

    public void display(String url, ImageView imageView, ScaleType scaleType) {
        display(url, imageView, R.drawable.ocupy, scaleType, null);
    }

    public void display(String url, ImageView imageView) {
        display(url, imageView, R.drawable.ocupy, ScaleType.FIT_XY, null);
    }

	//旋转图片 i表示角度
    public void display(String url, ImageView imageView, int i, boolean isHorizontal) {
        display(url, imageView, R.drawable.ocupy, ScaleType.FIT_XY, null, i);
    }

    public void display(String url, ImageView imageView, ScaleType scaleType, OnLoadingCompleteListener listener) {
        display(url, imageView, R.drawable.ocupy, scaleType, listener);
    }

	public void display(String url, ImageView imageView, OnLoadingCompleteListener listener) {
		display(url, imageView, R.drawable.ocupy, ScaleType.FIT_XY, listener);
	}

	public interface OnLoadingCompleteListener {
		void onLoadingComplete();
	}

}
