package com.zhaohaoting.framework.imagepicker.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.zhaohaoting.framework.R;
import com.zhaohaoting.framework.imagepicker.ImagePicker;
import com.zhaohaoting.framework.imagepicker.bean.MediaFolder;
import com.zhaohaoting.framework.imagepicker.bean.MediaItem;
import com.zhaohaoting.framework.imagepicker.util.Utils;
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;
import java.util.List;


/**
 * ================================================
 * 作    者：jeasonlzy（廖子尧 Github地址：https://github.com/jeasonlzy0216
 * 版    本：1.0
 * 创建日期：2016/5/19
 * 描    述：
 * 修订历史：
 * ================================================
 */
public class ImageFolderAdapter extends BaseAdapter {

    private ImagePicker imagePicker;
    private Activity mActivity;
    private LayoutInflater mInflater;
    private int mImageSize;
    private List<MediaFolder> imageFolders;
    private int lastSelected = 0;

    public ImageFolderAdapter(Activity activity, List<MediaFolder> folders) {
        mActivity = activity;
        if (folders != null && folders.size() > 0) imageFolders = folders;
        else imageFolders = new ArrayList<>();

        imagePicker = ImagePicker.getInstance();
        mImageSize = Utils.getImageItemWidth(mActivity);
        mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void refreshData(List<MediaFolder> folders) {
        if (folders != null && folders.size() > 0) imageFolders = folders;
        else imageFolders.clear();
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return imageFolders.size();
    }

    @Override
    public MediaFolder getItem(int position) {
        return imageFolders.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.adapter_folder_list_item, parent, false);
            holder = new ViewHolder(convertView);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        MediaFolder folder = getItem(position);
        holder.folderName.setText(folder.name);
        holder.imageCount.setText(mActivity.getString(R.string.ip_folder_image_count, folder.images.size()));
//        imagePicker.getImageLoader().displayImage(mActivity, folder.cover.thumbnailPath, holder.cover, mImageSize, mImageSize);
        if (folder.cover == null) {
            if (folder.images != null && folder.images.size() > 0) {
                MediaItem mediaItem = folder.images.get(0);
                imagePicker.getImageLoader().displayImage(mActivity, TextUtils.isEmpty(mediaItem.thumbnailPath) ? mediaItem.path : mediaItem.thumbnailPath, holder.cover, mImageSize, mImageSize); //显示图片
            }
        } else if (folder.cover.mediaType == ImagePicker.MEDIA_TYPE_IMAGE) {
            imagePicker.getImageLoader().displayImage(mActivity, TextUtils.isEmpty(folder.cover.thumbnailPath) ? folder.cover.path : folder.cover.thumbnailPath, holder.cover, mImageSize, mImageSize); //显示图片
        } else {
            File file = new File(mActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES), MD5.getStringMD5(folder.cover.path));
            if (!TextUtils.isEmpty(folder.cover.thumbnailPath)) {
                imagePicker.getImageLoader().displayImage(mActivity, folder.cover.thumbnailPath, holder.cover, mImageSize, mImageSize); //显示图片
            } else if (file.exists()) {
                imagePicker.getImageLoader().displayImage(mActivity, file.getAbsolutePath(), holder.cover, mImageSize, mImageSize); //显示图片
            } else {
                new ImageTask(holder.cover, mImageSize).execute(folder.cover);
            }
        }
        if (lastSelected == position) {
            holder.folderCheck.setVisibility(View.VISIBLE);
        } else {
            holder.folderCheck.setVisibility(View.INVISIBLE);
        }

        return convertView;
    }

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

        private WeakReference<ImageView> imageView;
        private int mImageSize;

        public ImageTask(ImageView imageView, int mImageSize) {
            this.imageView = new WeakReference<>(imageView);
            this.mImageSize = mImageSize;
        }

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

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

        //获取视频缩略图
        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();
        }
    }

    public void setSelectIndex(int i) {
        if (lastSelected == i) {
            return;
        }
        lastSelected = i;
        notifyDataSetChanged();
    }

    public int getSelectIndex() {
        return lastSelected;
    }

    private class ViewHolder {
        ImageView cover;
        TextView folderName;
        TextView imageCount;
        ImageView folderCheck;

        public ViewHolder(View view) {
            cover = (ImageView) view.findViewById(R.id.iv_cover);
            folderName = (TextView) view.findViewById(R.id.tv_folder_name);
            imageCount = (TextView) view.findViewById(R.id.tv_image_count);
            folderCheck = (ImageView) view.findViewById(R.id.iv_folder_check);
            view.setTag(this);
        }
    }
}
