package com.zhaohaoting.framework.imagepicker;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.MediaStore;

import com.zhaohaoting.framework.R;
import com.zhaohaoting.framework.ZhtLibrary;
import com.zhaohaoting.framework.imagepicker.bean.MediaFolder;
import com.zhaohaoting.framework.imagepicker.bean.MediaItem;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * author：Created by zhaohaoting on 2018/12/10 11:51
 * email：526309416@qq.com
 * desc：此处修改为加载中展示数据
 */

public class ImageDataSource extends AsyncTask<Integer, List<MediaItem>, Integer> {

    public static final int LOADER_ALL = 0;         //加载所有图片
    public static final int LOADER_CATEGORY = 1;    //分类加载图片

    private final String[] MEDIA_PROJECTION = {     //查询视频需要的数据列
            MediaStore.Files.FileColumns.DISPLAY_NAME,   //视频的显示名称  aaa.jpg
            MediaStore.Files.FileColumns.DATA,           //视频的真实路径  /storage/emulated/0/pp/downloader/wallpaper/aaa.jpg
            MediaStore.Files.FileColumns.SIZE,           //视频的大小，long型  132492
            MediaStore.Files.FileColumns.WIDTH,          //视频的宽度，int型  1920
            MediaStore.Files.FileColumns.HEIGHT,         //视频的高度，int型  1080
            MediaStore.Files.FileColumns.MIME_TYPE,      //视频的类型     video/jpeg
            MediaStore.Files.FileColumns.DATE_ADDED, //视频被添加的时间，long型  1450518608
            MediaStore.Files.FileColumns._ID,
            MediaStore.Files.FileColumns.TITLE,
            MediaStore.Video.Media.DURATION,

            MediaStore.Files.FileColumns.MEDIA_TYPE,

    };

    private ContentResolver resolver;
    private OnImagesLoadedListener loadedListener;                     //图片加载完成的回调接口
    private ArrayList<MediaFolder> mediaFolders = new ArrayList<>();   //所有的图片文件夹
    private String path;
    private int mediaType;
    private ArrayList<MediaItem> allMedias = new ArrayList<>();
    private MediaFolder allImagesFolder = new MediaFolder();//所有
    private OnMediaDataUpdateLinstener onMediaDataUpdateListener;
    public static final int FIRST_NOTIFY_SIZE = 50;

    /**
     * @param path           指定扫描的文件夹目录，可以为 null，表示扫描所有图片
     * @param loadedListener 图片加载完成的监听
     */
    public ImageDataSource(ContentResolver resolver, String path, OnImagesLoadedListener loadedListener, OnMediaDataUpdateLinstener mediaDataUpdateLinstener) {
        this.resolver = resolver;
        this.mediaType = ImagePicker.getInstance().getMediaType();
        this.path = path;
        this.loadedListener = loadedListener;
        this.onMediaDataUpdateListener = mediaDataUpdateLinstener;
    }

    public void setOnMediaDataUpdateListener(OnMediaDataUpdateLinstener onMediaDataUpdateListener) {
        this.onMediaDataUpdateListener = onMediaDataUpdateListener;
    }

    public interface OnMediaDataUpdateLinstener {

        void onDataUpdate(List<MediaItem> data);

    }

    @Override
    protected Integer doInBackground(Integer... integers) {
        String selection;
        String[] selectionArgs;
        //扫描所有图片
        if (path == null) {
            if (mediaType == ImagePicker.MEDIA_TYPE_IMAGE) {
                selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "=?";
                selectionArgs = new String[]{String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE)};
            } else if (mediaType == ImagePicker.MEDIA_TYPE_VIDEO) {
                selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "=?";
                selectionArgs = new String[]{String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO)};
            } else {
                selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "=?" + " OR " + MediaStore.Files.FileColumns.MEDIA_TYPE + "=?";
                selectionArgs = new String[]{String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE), String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO)};
            }
        } else {
            //扫描某个图片文件夹
            if (mediaType == ImagePicker.MEDIA_TYPE_IMAGE) {
                selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "=?" + MEDIA_PROJECTION[1] + " like '%?%'";
                selectionArgs = new String[]{String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE), path};
            } else if (mediaType == ImagePicker.MEDIA_TYPE_VIDEO) {
                selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "=?" + MEDIA_PROJECTION[1] + " like '%?%'";
                selectionArgs = new String[]{String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO), path};
            } else {
                selection = "(" + MediaStore.Files.FileColumns.MEDIA_TYPE + "=?" + " OR " + MediaStore.Files.FileColumns.MEDIA_TYPE + "=?)" + MEDIA_PROJECTION[1] + " like '%?%'";
                selectionArgs = new String[]{String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE), String.valueOf(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO), path};
            }
        }
        Cursor cursor = resolver.query(MediaStore.Files.getContentUri("external"), MEDIA_PROJECTION, selection, selectionArgs, MEDIA_PROJECTION[6] + " DESC");
        mediaFolders.clear();
        loadMedia(cursor);
        if (cursor != null) {
            cursor.close();
        }
        ImagePicker.getInstance().setImageFolders(mediaFolders);
        return 1;
    }

    @Override
    protected void onProgressUpdate(List<MediaItem>... values) {
        List<MediaItem> mediaItems = values[0];
        if (mediaItems != null) {
            allMedias.addAll(mediaItems);
            //构造所有图片的集合
            if (onMediaDataUpdateListener != null) {
                onMediaDataUpdateListener.onDataUpdate(mediaItems);
            }
        }
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        //回调接口，通知图片数据准备完成
        loadedListener.onImagesLoaded(mediaFolders);
    }

    private void loadMedia(Cursor cursor) {
        if (cursor == null) return;
        //需要排序
        if (!mediaFolders.contains(allImagesFolder)) {
            int mediaType = ImagePicker.getInstance().getMediaType();
            allImagesFolder.name = mediaType == ImagePicker.MEDIA_TYPE_IMAGE ? ZhtLibrary.getContext().getString(R.string.all_picture) : (mediaType == ImagePicker.MEDIA_TYPE_VIDEO ? ZhtLibrary.getContext().getString(R.string.all_video) : ZhtLibrary.getContext().getString(R.string.picture_and_video));
            allImagesFolder.path = "/";
            allImagesFolder.images = allMedias;
            mediaFolders.add(0, allImagesFolder);  //确保第一条是所有图片
        }
        List<MediaItem> cachedList = new ArrayList<>();
        int index = 0;
        while (cursor.moveToNext()) {
            MediaItem mediaInfo = getMediaInfo(cursor);
            if (mediaInfo == null) continue;
            cachedList.add(mediaInfo);
            index++;
            if (index % FIRST_NOTIFY_SIZE == 0) {
                publishProgress(cachedList);
                cachedList = new ArrayList<>();
            }
        }
        publishProgress(cachedList);
    }

    private MediaItem getMediaInfo(Cursor mediaData) {
        //查询数据
        String mediaName = mediaData.getString(mediaData.getColumnIndexOrThrow(MEDIA_PROJECTION[0]));
        String mediaPath = mediaData.getString(mediaData.getColumnIndexOrThrow(MEDIA_PROJECTION[1]));

        File file = new File(mediaPath);
        if (!file.exists() || file.length() <= 0) {
            return null;
        }

        long mediaSize = mediaData.getLong(mediaData.getColumnIndexOrThrow(MEDIA_PROJECTION[2]));
        int mediaWidth = mediaData.getInt(mediaData.getColumnIndexOrThrow(MEDIA_PROJECTION[3]));
        int mediaHeight = mediaData.getInt(mediaData.getColumnIndexOrThrow(MEDIA_PROJECTION[4]));
        String mediaMimeType = mediaData.getString(mediaData.getColumnIndexOrThrow(MEDIA_PROJECTION[5]));
        long mediaAddTime = mediaData.getLong(mediaData.getColumnIndexOrThrow(MEDIA_PROJECTION[6]));
        long mediaId = mediaData.getLong(mediaData.getColumnIndexOrThrow(MEDIA_PROJECTION[7]));
        long mediaTitle = mediaData.getLong(mediaData.getColumnIndexOrThrow(MEDIA_PROJECTION[8]));
        long mediaDuration = mediaData.getLong(mediaData.getColumnIndexOrThrow(MEDIA_PROJECTION[9]));
        long mediaType = mediaData.getLong(mediaData.getColumnIndexOrThrow(MEDIA_PROJECTION[10]));
        //封装实体
        MediaItem mediaItem = new MediaItem();
        mediaItem.name = mediaName;
        mediaItem.path = mediaPath;
        mediaItem.size = mediaSize;
        mediaItem.width = mediaWidth;
        mediaItem.height = mediaHeight;
        mediaItem.mimeType = mediaMimeType;
        mediaItem.addTime = mediaAddTime;
        mediaItem.mediaId = mediaId;
        mediaItem.mediaTitle = mediaTitle;
        mediaItem.videoDuration = mediaDuration;
        if (mediaType == MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) {
            mediaItem.mediaType = ImagePicker.MEDIA_TYPE_IMAGE;
        } else {
            mediaItem.mediaType = ImagePicker.MEDIA_TYPE_VIDEO;
        }
        //根据父路径分类存放图片
        File mediaFile = new File(mediaPath);
        File mediaParentFile = mediaFile.getParentFile();
        MediaFolder mediaFolder = new MediaFolder();
        mediaFolder.name = mediaParentFile.getName();
        mediaFolder.path = mediaParentFile.getAbsolutePath();

        if (!mediaFolders.contains(mediaFolder)) {
            ArrayList<MediaItem> videos = new ArrayList<>();
            videos.add(mediaItem);
            mediaFolder.cover = mediaItem;
            mediaFolder.images = videos;
            mediaFolders.add(mediaFolder);
        } else {
            mediaFolders.get(mediaFolders.indexOf(mediaFolder)).images.add(mediaItem);
        }
        return mediaItem;
    }

    /**
     * 所有图片加载完成的回调接口
     */
    public interface OnImagesLoadedListener {
        void onImagesLoaded(List<MediaFolder> imageFolders);
    }
}
