package com.zhaohaoting.framework.imagepicker;

import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;

import com.zhaohaoting.framework.R;
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;

/**
 * ================================================
 * 作    者：jeasonlzy（廖子尧 Github地址：https://github.com/jeasonlzy0216
 * 版    本：1.0
 * 创建日期：2016/5/19
 * 描    述：加载手机视频实现类
 * 修订历史：
 * ================================================
 */
public class VideoDataSource implements LoaderManager.LoaderCallbacks<Cursor> {

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

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

    private FragmentActivity activity;
    private OnVideosLoadedListener loadedListener;                     //图片加载完成的回调接口
    private ArrayList<MediaFolder> mediaFolders = new ArrayList<>();   //所有的视频文件夹

    /**
     * @param activity       用于初始化LoaderManager，需要兼容到2.3
     * @param path           指定扫描的文件夹目录，可以为 null，表示扫描所有图片
     * @param loadedListener 图片加载完成的监听
     */
    public VideoDataSource(FragmentActivity activity, String path, OnVideosLoadedListener loadedListener) {
        this.activity = activity;
        this.loadedListener = loadedListener;
        LoaderManager loaderManager = activity.getSupportLoaderManager();
        Bundle bundle = new Bundle();
        if (path == null) {
            loaderManager.initLoader(LOADER_ALL, null, this);//加载所有的图片
        } else {
            //加载指定目录的图片
            bundle.putString("path", path);
            loaderManager.initLoader(LOADER_CATEGORY, bundle, this);
        }
    }


    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        CursorLoader cursorLoader = null;
        //扫描所有图片
        if (id == LOADER_ALL)
            cursorLoader = new CursorLoader(activity, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION, null, null, VIDEO_PROJECTION[6] + " DESC");
        //扫描某个图片文件夹
        if (id == LOADER_CATEGORY)
            cursorLoader = new CursorLoader(activity, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION, VIDEO_PROJECTION[1] + " like '%" + args.getString("path") + "%'", null, VIDEO_PROJECTION[6] + " DESC");

        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mediaFolders.clear();
        if (data != null) {
            ArrayList<MediaItem> allVideos = new ArrayList<>();   //所有图片的集合,不分文件夹
            if (!data.moveToFirst()) {
                return;
            }
            while (data.moveToNext()) {
                //查询数据
                String videoName = data.getString(data.getColumnIndexOrThrow(VIDEO_PROJECTION[0]));
                String videoPath = data.getString(data.getColumnIndexOrThrow(VIDEO_PROJECTION[1]));

                File file = new File(videoPath);
                if (!file.exists() || file.length() <= 0) {
                    continue;
                }

                long videoSize = data.getLong(data.getColumnIndexOrThrow(VIDEO_PROJECTION[2]));
                int videoWidth = data.getInt(data.getColumnIndexOrThrow(VIDEO_PROJECTION[3]));
                int videoHeight = data.getInt(data.getColumnIndexOrThrow(VIDEO_PROJECTION[4]));
                String videoMimeType = data.getString(data.getColumnIndexOrThrow(VIDEO_PROJECTION[5]));
                long videoAddTime = data.getLong(data.getColumnIndexOrThrow(VIDEO_PROJECTION[6]));
                long videoId = data.getLong(data.getColumnIndexOrThrow(VIDEO_PROJECTION[7]));
                long videoTitle = data.getLong(data.getColumnIndexOrThrow(VIDEO_PROJECTION[8]));
                long videoDuration = data.getLong(data.getColumnIndexOrThrow(VIDEO_PROJECTION[9]));
                //封装实体
                MediaItem videoItem = new MediaItem();
                videoItem.name = videoName;
                videoItem.path = videoPath;
                videoItem.size = videoSize;
                videoItem.width = videoWidth;
                videoItem.height = videoHeight;
                videoItem.mimeType = videoMimeType;
                videoItem.addTime = videoAddTime;
                videoItem.mediaId = videoId;
                videoItem.mediaTitle = videoTitle;
                videoItem.videoDuration = videoDuration;
                videoItem.mediaType = ImagePicker.MEDIA_TYPE_VIDEO;
                allVideos.add(videoItem);
                //根据父路径分类存放图片
                File videoFile = new File(videoPath);
                File videoParentFile = videoFile.getParentFile();
                MediaFolder videoFolder = new MediaFolder();
                videoFolder.name = videoParentFile.getName();
                videoFolder.path = videoParentFile.getAbsolutePath();

                if (!mediaFolders.contains(videoFolder)) {
                    ArrayList<MediaItem> videos = new ArrayList<>();
                    videos.add(videoItem);
                    videoFolder.cover = videoItem;
                    videoFolder.images = videos;
                    mediaFolders.add(videoFolder);
                } else {
                    mediaFolders.get(mediaFolders.indexOf(videoFolder)).images.add(videoItem);
                }
            }
            //防止没有图片报异常
            if (data.getCount() > 0 && allVideos.size() > 0) {
                //构造所有图片的集合
                MediaFolder allVideosFolder = new MediaFolder();
                allVideosFolder.name = activity.getResources().getString(R.string.ip_all_images);
                allVideosFolder.path = "/";
                allVideosFolder.cover = allVideos.get(0);
                allVideosFolder.images = allVideos;
                mediaFolders.add(0, allVideosFolder);  //确保第一条是所有图片
            }
        }

        //回调接口，通知数据准备完成
        ImagePicker.getInstance().setImageFolders(mediaFolders);
        loadedListener.onVideoLoaded(mediaFolders);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        System.out.println("--------");
    }

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