package com.sheep.gamegroup.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by realicing on 2018/11/29.
 * realicing@sina.com
 * 可以获取视频帧
 */
public class MediaMetadataRetrieverUtil {
    private static final String TAG = "MediaMetadataRetrieverUtil";
    //要操作的本地视频文件
    private String fromFile;
    //输出路径
    private String outDir = SheepApp.getInstance().getDir("frame", Context.MODE_PRIVATE).getAbsolutePath();
    //视频文件的总时长，单位毫秒
    private long duration;
    //要截取的图片个数
    private int size = 10;

    public MediaMetadataRetrieverUtil(String fromFile, long duration) {
        this.fromFile = fromFile;
        this.duration = duration;
    }

    public String getFromFile() {
        return fromFile;
    }

    public void setFromFile(String fromFile) {
        this.fromFile = fromFile;
    }

    public String getOutDir() {
        return outDir;
    }

    public void setOutDir(String outDir) {
        this.outDir = outDir;
    }

    public long getDuration() {
        return duration;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    /**
     * 取出视频文件中的图片帧列表
     */
    public void initRv(final RecyclerView recyclerView) {
        Observable.create(new ObservableOnSubscribe<List<Bitmap>>() {
            @Override
            public void subscribe(ObservableEmitter<List<Bitmap>> emitter) throws Exception {
                emitter.onNext(getFrameBitmapList(fromFile, duration, size));
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new AbsObserver<List<Bitmap>>() {
                    @Override
                    public void onNext(final List<Bitmap> strings) {
                        recyclerView.setLayoutManager(new GridLayoutManager(SheepApp.getInstance(), size));
                        BaseQuickAdapter<Bitmap, BaseViewHolder> baseQuickAdapter = new BaseQuickAdapter<Bitmap, BaseViewHolder>(R.layout.item_iv_mh, strings) {
                            @Override
                            protected void convert(BaseViewHolder helper, Bitmap item) {
                                ImageView imageView = helper.getView(R.id.item_iv);
                                imageView.setImageBitmap(item);
                            }
                        };
                        recyclerView.setAdapter(baseQuickAdapter);
                    }
                });

    }
    /**
     * 取出视频文件中的图片帧列表
     */
    public void initRv2(final RecyclerView recyclerView) {
        Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) throws Exception {
                emitter.onNext(getFrameFileList(fromFile, outDir, duration, size));
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new AbsObserver<List<String>>() {
                    @Override
                    public void onNext(final List<String> strings) {
                        recyclerView.setLayoutManager(new GridLayoutManager(SheepApp.getInstance(), size));
                        BaseQuickAdapter<String, BaseViewHolder> baseQuickAdapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_iv_mh, strings) {
                            @Override
                            protected void convert(BaseViewHolder helper, String item) {
                                ImageView imageView = helper.getView(R.id.item_iv);
                                ViewUtil.setImagePath(imageView, item);
                                Jump2View.getInstance().showImgList(ActivityManager.getInstance().currentActivity(), helper.getAdapterPosition(), (ArrayList<String>) strings);
                            }
                        };
                        recyclerView.setAdapter(baseQuickAdapter);
                    }
                });

    }


    public static String getFilePath(String fromFile, String outDir, int index) {
        return String.format(Locale.CHINA, "%s%s%s_frame_%d.png", outDir, File.separator, FileUtil.getFileNameNoExFromPath(fromFile), index);
    }

    /**
     * 取出视频文件中的图片帧列表
     *
     * @param fromFile 要操作的本地视频文件
     * @param duration 视频文件的总时长，单位毫秒
     * @param size     需要的图片个数
     * @return
     */
    public static List<Bitmap> getFrameBitmapList(String fromFile, long duration, int size) {
        if (duration < size || size < 1) {
            return null;
        }
        try {
            long per = duration * 1000L / (size - 1);
            List<Bitmap> resultList = new ArrayList<>();
            long time = System.currentTimeMillis();
            MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
            metadataRetriever.setDataSource(SheepApp.getInstance(), Uri.parse(fromFile));
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
                MediaMetadataRetriever.BitmapParams bitmapParams = new MediaMetadataRetriever.BitmapParams();
                Bitmap.Config config = Bitmap.Config.ARGB_8888;
                bitmapParams.setPreferredConfig(config);
                return metadataRetriever.getFramesAtIndex(0, size, bitmapParams);
            }
            for (int i = 0; i < size; i++) {
                //这里单位为微秒
                long atTime = i + 1 == size ? (duration * 1000L) : i * per;
                Bitmap bitmap = metadataRetriever.getFrameAtTime(atTime, MediaMetadataRetriever.OPTION_CLOSEST);
                resultList.add(bitmap);
            }
            long curTime = System.currentTimeMillis();
            LogUtil.println(TAG, time, curTime, curTime - time, (curTime - time) / 1000, (curTime - time) / 10000);
            return resultList;
        }catch (Exception e){
            e.printStackTrace();
            LogUtil.println(MediaMetadataRetrieverUtil.class.getSimpleName(), "getFrameBitmapList", e.getMessage());
        }
        return null;
    }

    /**
     * 取出视频文件中的图片帧列表
     *
     * @param fromFile 要操作的本地视频文件
     * @param outDir   输出路径
     * @param duration 视频文件的总时长，单位毫秒
     * @param size     需要的图片个数
     * @return
     */
    public static List<String> getFrameFileList(String fromFile, String outDir, long duration, int size) {
        if (duration < size || size < 1) {
            return null;
        }
        long per = duration * 1000L / (size - 1);
        List<String> resultList = new ArrayList<>();
        long time = System.currentTimeMillis();
        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
        metadataRetriever.setDataSource(SheepApp.getInstance(), Uri.parse(fromFile));

        for (int i = 0; i < size; i++) {
            //这里单位为微秒
            long atTime = i + 1 == size ? (duration * 1000L) : i * per;
            Bitmap bitmap = metadataRetriever.getFrameAtTime(atTime, MediaMetadataRetriever.OPTION_CLOSEST);

            String path = getFilePath(fromFile, outDir, i);
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(path);
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, fileOutputStream);
                resultList.add(path);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(bitmap != null)
                    bitmap.recycle();
            }
        }
        long curTime = System.currentTimeMillis();
        LogUtil.println(TAG, time, curTime, curTime - time, (curTime - time) / 1000, (curTime - time) / 10000);
        return resultList;
    }
}
