package com.zhaohaoting.framework.imagepicker.adapter;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhaohaoting.framework.R;
import com.zhaohaoting.framework.imagepicker.ImagePicker;
import com.zhaohaoting.framework.imagepicker.bean.MediaItem;
import com.zhaohaoting.framework.imagepicker.camera.JCameraView;
import com.zhaohaoting.framework.imagepicker.ui.CameraActivity;
import com.zhaohaoting.framework.imagepicker.ui.ImageBaseActivity;
import com.zhaohaoting.framework.imagepicker.ui.ImageGridActivity;
import com.zhaohaoting.framework.imagepicker.util.Utils;
import com.zhaohaoting.framework.imagepicker.view.SuperCheckBox;
import com.zhaohaoting.framework.utils.md5.MD5;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * 加载相册图片的RecyclerView适配器
 * <p>
 * 用于替换原项目的GridView，使用局部刷新解决选中照片出现闪动问题
 * <p>
 * 替换为RecyclerView后只是不再会导致全局刷新，
 * <p>
 * 但还是会出现明显的重新加载图片，可能是picasso图片加载框架的问题
 * <p>
 * Author: nanchen
 * Email: liushilin520@foxmail.com
 * Date: 2017-04-05  10:04
 */

public class ImageRecyclerAdapter extends RecyclerView.Adapter<ViewHolder> {


    private static final int ITEM_TYPE_CAMERA = 0;  //第一个条目是相机
    private static final int ITEM_TYPE_NORMAL = 1;  //第一个条目不是相机
    private ImagePicker imagePicker;
    private Activity mActivity;
    private ArrayList<MediaItem> images;       //当前需要显示的所有的图片数据
    private ArrayList<MediaItem> mSelectedImages; //全局保存的已经选中的图片数据
    private boolean isShowCamera;         //是否显示拍照按钮
    private int mImageSize;               //每个条目的大小
    private LayoutInflater mInflater;
    private OnImageItemClickListener listener;   //图片被点击的监听
    private final ContentResolver contentResolver;
    private final String sDurationFormat;

    public void setOnImageItemClickListener(OnImageItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnImageItemClickListener {
        void onImageItemClick(View view, MediaItem imageItem, int position);
    }

    public void refreshData(ArrayList<MediaItem> images) {
        if (images == null || images.size() == 0) this.images = new ArrayList<>();
        else this.images = images;
        notifyDataSetChanged();
    }

    public void addData(ArrayList<MediaItem> images) {
        if (this.images == null) this.images = new ArrayList<>();
        else this.images.addAll(images);
        int size = this.images.size();
        int count = images.size();
        if (size > count) {
//            notifyItemRangeChanged(size - count, count);
            notifyItemRangeInserted(size - count, count);
        } else {
            notifyDataSetChanged();
        }
    }

    /**
     * 构造方法
     */
    public ImageRecyclerAdapter(Activity activity, ArrayList<MediaItem> images) {
        this.mActivity = activity;
        if (images == null || images.size() == 0) this.images = new ArrayList<>();
        else this.images = images;

        mImageSize = Utils.getImageItemWidth(mActivity);
        imagePicker = ImagePicker.getInstance();
        isShowCamera = imagePicker.isShowCamera();
        mSelectedImages = imagePicker.getSelectedImages();
        mInflater = LayoutInflater.from(activity);
        contentResolver = activity.getContentResolver();
        sDurationFormat = activity.getResources().getString(R.string.video_duration);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE_CAMERA) {
            return new CameraViewHolder(mInflater.inflate(R.layout.adapter_camera_item, parent, false));
        }
        return new ImageViewHolder(mInflater.inflate(R.layout.adapter_image_list_item, parent, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (holder instanceof CameraViewHolder) {
            ((CameraViewHolder) holder).bindCamera();
        } else if (holder instanceof ImageViewHolder) {
            ((ImageViewHolder) holder).bind(position);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (isShowCamera) return position == 0 ? ITEM_TYPE_CAMERA : ITEM_TYPE_NORMAL;
        return ITEM_TYPE_NORMAL;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return isShowCamera ? images.size() + 1 : images.size();
    }

    public MediaItem getItem(int position) {
        if (isShowCamera) {
            if (position == 0) return null;
            return images.get(position - 1);
        } else {
            return images.get(position);
        }
    }

    private class ImageViewHolder extends ViewHolder {

        View rootView;
        ImageView ivThumb;
        TextView tvDuration;
        View mask;
        View checkView;
        SuperCheckBox cbCheck;


        ImageViewHolder(View itemView) {
            super(itemView);
            rootView = itemView;
            ivThumb = (ImageView) itemView.findViewById(R.id.iv_thumb);
            tvDuration = itemView.findViewById(R.id.tv_duration);
            mask = itemView.findViewById(R.id.mask);
            checkView = itemView.findViewById(R.id.checkView);
            cbCheck = (SuperCheckBox) itemView.findViewById(R.id.cb_check);
            itemView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mImageSize)); //让图片是个正方形
        }

        void bind(final int position) {
            final MediaItem imageItem = getItem(position);
//            Logger.e("MediaItem", position + "-------------------------------->" + imageItem);
            if (imageItem.mediaType == ImagePicker.MEDIA_TYPE_VIDEO) {
                int sec = Math.round(((float) imageItem.videoDuration) / 1000);
                int hour = sec / 3600;
                int min = (sec % 3600) / 60;
                sec = (sec % 60);
                tvDuration.setText(String.format(sDurationFormat, hour, min, sec));
            } else {
                tvDuration.setText("");
            }

            ivThumb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) listener.onImageItemClick(rootView, imageItem, position);
                }
            });
            checkView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    cbCheck.setChecked(!cbCheck.isChecked());
                    int selectLimit = imagePicker.getSelectLimit();
                    if (cbCheck.isChecked() && mSelectedImages.size() >= selectLimit) {
                        Toast.makeText(mActivity.getApplicationContext(), mActivity.getString(R.string.ip_select_limit, selectLimit), Toast.LENGTH_SHORT).show();
                        cbCheck.setChecked(false);
                        mask.setVisibility(View.GONE);
                    } else {
                        imagePicker.addSelectedImageItem(position, imageItem, cbCheck.isChecked());
                        mask.setVisibility(View.VISIBLE);
                    }
                }
            });
            //根据是否多选，显示或隐藏checkbox
            if (imagePicker.isMultiMode()) {
                cbCheck.setVisibility(View.VISIBLE);
                boolean checked = mSelectedImages.contains(imageItem);
                if (checked) {
                    mask.setVisibility(View.VISIBLE);
                    cbCheck.setChecked(true);
                } else {
                    mask.setVisibility(View.GONE);
                    cbCheck.setChecked(false);
                }
            } else {
                cbCheck.setVisibility(View.GONE);
            }
            if (imageItem.mediaType == ImagePicker.MEDIA_TYPE_IMAGE) {
                imagePicker.getImageLoader().displayImage(mActivity, TextUtils.isEmpty(imageItem.thumbnailPath) ? imageItem.path : imageItem.thumbnailPath, ivThumb, mImageSize, mImageSize); //显示图片
            } else {
                File file = new File(mActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES), MD5.getStringMD5(imageItem.path));
                rootView.setTag(file.getAbsolutePath());
                if (!TextUtils.isEmpty(imageItem.thumbnailPath)) {
                    imagePicker.getImageLoader().displayImage(mActivity, imageItem.thumbnailPath, ivThumb, mImageSize, mImageSize); //显示图片
                } else if (file.exists()) {
                    imagePicker.getImageLoader().displayImage(mActivity, file.getAbsolutePath(), ivThumb, mImageSize, mImageSize); //显示图片
                } else {
                    ivThumb.setImageResource(R.mipmap.default_place_holder);
                    new ImageTask(ivThumb, rootView, imagePicker, mImageSize).execute(imageItem);
                }
            }
        }
    }

    private static class ImageTask extends AsyncTask<MediaItem, Bitmap, String> {

        private WeakReference<ImageView> imageView;
        private WeakReference<View> rootView;
        private ImagePicker imagePicker;
        private int mImageSize;

        ImageTask(ImageView imageView, View rootView, ImagePicker imagePicker, int mImageSize) {
            this.imageView = new WeakReference<>(imageView);
            this.rootView = new WeakReference<>(rootView);
            this.imagePicker = imagePicker;
            this.mImageSize = mImageSize;
        }

        @Override
        protected String doInBackground(MediaItem... values) {
            MediaItem value = values[0];
            return getVideoThumbnail(value);
        }

        @Override
        protected void onPostExecute(String thumbnailPath) {
            super.onPostExecute(thumbnailPath);
            if (!TextUtils.isEmpty(thumbnailPath) && thumbnailPath.equals(rootView.get().getTag())) {
                imagePicker.getImageLoader().displayImage((Activity) imageView.get().getContext(), thumbnailPath, imageView.get(), mImageSize, mImageSize); //显示图片
            }
        }

        @Override
        protected void onProgressUpdate(Bitmap... values) {
            super.onProgressUpdate(values);
        }

        //获取视频缩略图
        private String getVideoThumbnail(MediaItem mediaItem) {
            Bitmap frameAtTime = ThumbnailUtils.createVideoThumbnail(mediaItem.path, 1);
            if (imageView.get() == null) return null;
            File file = new File(imageView.get().getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), MD5.getStringMD5(mediaItem.path));
            if (frameAtTime != null) {
                if (!file.exists()) {
                    File parentFile = file.getParentFile();
                    if (!parentFile.exists()) {
                        boolean mkdirs = parentFile.mkdirs();
                    }
                } else {
                    boolean delete = file.delete();
                }
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);
                    frameAtTime.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return file.getAbsolutePath();
        }
    }

    private class CameraViewHolder extends ViewHolder {

        View mItemView;

        CameraViewHolder(View itemView) {
            super(itemView);
            mItemView = itemView;
        }

        void bindCamera() {
            mItemView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mImageSize)); //让图片是个正方形
            mItemView.setTag(null);
            mItemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ImagePicker.getInstance().getMediaType() == ImagePicker.MEDIA_TYPE_IMAGE) {
                        if (!((ImageBaseActivity) mActivity).checkPermission(Manifest.permission.CAMERA)) {
                            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.CAMERA}, ImageGridActivity.REQUEST_PERMISSION_CAMERA);
                        } else {
                            imagePicker.takePicture(mActivity, ImagePicker.REQUEST_CODE_TAKE);
                        }
                    } else {
                        if (!((ImageBaseActivity) mActivity).checkPermission(Manifest.permission.CAMERA) && !((ImageBaseActivity) mActivity).checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) && !((ImageBaseActivity) mActivity).checkPermission(Manifest.permission.RECORD_AUDIO)) {
                            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO}, ImageGridActivity.REQUEST_PERMISSION_CAMERA);
                        } else {
                            mActivity.startActivityForResult(new Intent(mActivity, CameraActivity.class).putExtra("state", JCameraView.BUTTON_STATE_ONLY_RECORDER), ImagePicker.RESULT_CODE_RECORDING);
                        }
                    }
                }
            });
        }
    }
}
