package com.example.myapplication;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.ListView;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

public class ImageLoader {

    private ImageView mImageView;
    private String murl;
    //创建Cache
    private LruCache<String, Bitmap> mCaches;
    private ListView mListView;
    private Set<NewsAsyncTask> mTask;

    public ImageLoader(ListView listView){
        //构造方法
        mListView = listView;
        mTask = new HashSet<>();
        //获取最大可用内存
        int  maxMemory = (int) Runtime.getRuntime().maxMemory();
        //缓存为内存的四分之一
        int cacheSize = maxMemory / 4;
        mCaches = new LruCache<String, Bitmap>(cacheSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                //每次加入内存缓存的时候进行调用,把value的实际大小放进去
                return value.getByteCount();
            }
        };

    }

    /**
     * 增加到缓存
     * @param url
     * @param bitmap
     */
    public void addBitmapToCache(String url, Bitmap bitmap){
        //判断缓存中是否有这个值
        if(getBitmapFromCache(url) == null){
            mCaches.put(url, bitmap);
        }
    }

    /**
     * 从缓存中读取数据
     * @param url
     * @return
     */
    public Bitmap getBitmapFromCache(String url){
        //获取缓存的对象
        return mCaches.get(url);
    }

//    private Handler handler = new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            //接受message
//            if(mImageView.getTag().equals(murl)) {
//                //url相同的时候才设置view，防止图片一样
//                mImageView.setImageBitmap((Bitmap) msg.obj);
//            }
//        }
//    };
//
//    public void showImagerByThread(ImageView imageView, final String url){
//        //把两个值保存给上面的子线程使用
//        mImageView = imageView;
//        murl = url;
//        new Thread(){
//            @Override
//            public void run() {
//                super.run();
//                Bitmap bitmap = getBitmapFromURL(url);
//                Message message = Message.obtain();
//                message.obj = bitmap;
//                //发送message
//                handler.sendMessage(message);
//            }
//        }.start();
//    }

    /**
     * 根据url获取图片的Bitmap对象
     * @param urlString
     * @return
     */
    public Bitmap getBitmapFromURL(String urlString){
        Bitmap bitmap;
        InputStream is = null;
        try {
            URL url = new URL(urlString);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            is = new BufferedInputStream(connection.getInputStream());
            bitmap = BitmapFactory.decodeStream(is);
            connection.disconnect();
            return bitmap;
        } catch (java.io.IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public void showImageByAsyncTask(ImageView imageView,String url){
        //判断缓存中是否有
        Bitmap bitmap = getBitmapFromCache(url);
        if(bitmap == null){
            //缓存中没有就去下载
            //new NewsAsyncTask(imageView, url).execute(url);

            //没有就给默认的
            imageView.setImageResource(R.mipmap.ic_launcher);
        }else{
            imageView.setImageBitmap(bitmap);
        }

    }

    /**
     * 停止运行的任务
     */
    public void cancelAllTasks(){
        if(mTask != null){
            for (NewsAsyncTask task : mTask){
                task.cancel(false);
            }
        }
    }
    
    public void loadImages(int start, int end){
        for (int i = start; i < end; i++) {
            String url = NewsAdapter.URLS[i];
            //判断缓存中是否有
            Bitmap bitmap = getBitmapFromCache(url);
            if(bitmap == null){
                //缓存中没有就去下载
                //new NewsAsyncTask(imageView, url).execute(url);
                NewsAsyncTask task = new NewsAsyncTask(url);
                task.execute(url);
                mTask.add(task);
            }else{
                //imageView.setImageBitmap(bitmap);
                ImageView imageView = mListView.findViewWithTag(url);
                imageView.setImageBitmap(bitmap);
            }
        }
    }

    /**
     * AsyncTask的方式把图片放入view
     */
    private class NewsAsyncTask extends AsyncTask<String, Void, Bitmap>{

        //private ImageView mImageView;
        private String murl;

        public NewsAsyncTask(String url){
            //mImageView = imageView;
            murl = url;
        }

        @Override
        protected Bitmap doInBackground(String... strings) {
            String url = strings[0];
            //从网络中获取图片
            Bitmap bitmap = getBitmapFromURL(url);
            if(bitmap != null){
                //增加到缓存
                addBitmapToCache(url, bitmap);
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            //防止图片重复判断唯一性
//            if(mImageView.getTag().equals(murl)) {
//                mImageView.setImageBitmap(bitmap);
//            }
            ImageView imageView = mListView.findViewWithTag(murl);
            imageView.setImageBitmap(bitmap);
            if(imageView != null && bitmap != null){
                imageView.setImageBitmap(bitmap);
            }
            mTask.remove(this);
        }
    }
}
