package com.android.chmo.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;

import com.android.chmo.ui.adpater.CommonAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/8/15.
 */

public class LongImageView extends ListView {

    private List<Bitmap> mList = new ArrayList<>();

    public LongImageView(Context context) {
        super(context);
        init();
    }
    public LongImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setDividerHeight(0);
        setCacheColorHint(Color.TRANSPARENT);
    }

    public void onDestroy() {
        for (Bitmap bm : mList) {
            bm.recycle();
            bm = null;
        }
        mList.clear();
    }


    public void setImage(Bitmap bitmap) {
        float width = bitmap.getWidth();
        float height = bitmap.getHeight();
        int count = (int)Math.ceil(height / width);
        for (int i=0; i < count; i++) {
            Bitmap bm = cropBitmap(bitmap, (int)(i* width), (int)width);
            mList.add(bm);
        }
        BitmapAdapter adapter = new BitmapAdapter();
        setAdapter(adapter);
        adapter.setList(mList);
    }


    private Bitmap cropBitmap(Bitmap bitmap, int y, int size) {
        try {
            int height = bitmap.getHeight();
            int cropW = size;
            int cropH = size;
            if(y+size > height) {
                cropH = height-y;
            }
            return Bitmap.createBitmap(bitmap, 0, y, cropW, cropH, null, false);
        }catch (OutOfMemoryError e){
            System.gc();
            System.runFinalization();
            return cropBitmap(bitmap, y,size);
        }
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 从屏幕中消失时回调,加快内容回收
        onDestroy();
    }


    private class BitmapAdapter extends CommonAdapter<Bitmap> {

        @Override
        public View getItemView(int position, View convertView, ViewGroup parent) {
            RecyclableImageView imageView = null;
            if(convertView == null) {
                imageView = new RecyclableImageView(getContext());
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                imageView.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                convertView = imageView;
            }else {
                imageView = (RecyclableImageView) convertView;
            }
            imageView.setImageBitmap(mList.get(position));
            return convertView;
        }
    }
}
