package com.kfzs.cfyl.media.customview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.VideoBitmapDecoder;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.kfzs.cfyl.media.R;
import com.kfzs.cfyl.media.bean.VideoFrame;
import com.kfzs.cfyl.media.glide.VideoFrameTransform;
import com.kfzs.cfyl.media.util.ViewUtil;
import com.kfzs.cfyl.share_library.util.LogUtil;
import com.sheep.gamegroup.model.entity.Video;

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

import rx.functions.Action1;


/**
 * Created by realicing on 2018/11/29.
 * realicing@sina.com
 * 显示本地视频文件对应的视频帧
 */
public class VideoFramesView extends RelativeLayout {
    public VideoFramesView(Context context) {
        super(context);
        initView();
    }

    public VideoFramesView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public VideoFramesView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private RecyclerView recyclerView;
    private View line_start;
    private View line_end;

    private void initView() {
        LayoutInflater.from(getContext()).inflate(R.layout.media_custom_video_frames_view, this, true);
        recyclerView = findViewById(R.id.media_recyclerView);
        line_start = findViewById(R.id.line_start);
        line_end = findViewById(R.id.line_end);
        recyclerView.setOnTouchListener(new OnTouchListener() {
            private View view;
            private OnTouchListener onTouchListener;
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        float x = event.getX();
                        if(Math.abs(x - line_start.getX()) > Math.abs(x - line_end.getX())){
                            view = line_end;
                            onTouchListener = endOnTouchListener;
                        } else {
                            view = line_start;
                            onTouchListener = startOnTouchListener;
                        }
                        break;
                }
                if(view != null){
                    MotionEvent motionEvent = MotionEvent.obtain(event.getDownTime(), event.getEventTime(), event.getAction(), event.getX() - view.getX(), event.getY(),event.getMetaState());
                    return onTouchListener.onTouch(view, motionEvent);
                }
                return false;
            }
        });
        line_start.setOnTouchListener(startOnTouchListener);
        line_end.setOnTouchListener(endOnTouchListener);
    }

    private OnTouchListener endOnTouchListener = new OnTouchListener() {
        private float lastEventX;

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            float minX = line_start.getX();
            float maxX = firstEndX - firstStartX + minX;
            float endX = firstStartX + rvW - lineW;
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    lastEventX = event.getX();
                    break;
                case MotionEvent.ACTION_MOVE:
                    float mx = Math.min(view.getX() + event.getX() - lastEventX, endX);
                    if (mx < minX)
                        mx = minX;
                    if (mx > maxX) {
                        minX += mx - maxX;
                        line_start.setX(minX);
                        view.setX(mx);
                    } else {
                        view.setX(mx);
                    }
                    if (onTimeChangeListener != null) {
                        onTimeChangeListener.call((mx - minX) * video.getDuration() / (rvW - lineW));
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    break;
                case MotionEvent.ACTION_CANCEL:
                    break;
            }
            view.invalidate();
            return true;
        }
    };
    private OnTouchListener startOnTouchListener = new OnTouchListener() {
        private float lastEventX;

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            float maxX = line_end.getX();
            float minX = maxX - (firstEndX - firstStartX);//结束位置 - 可以设置的长度
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    lastEventX = event.getX();
                    break;
                case MotionEvent.ACTION_MOVE:
                    float mx = Math.max(firstStartX, view.getX() + event.getX() - lastEventX);
                    if (mx > maxX)
                        mx = maxX;
                    if (mx < minX) {
                        maxX += mx - minX;
                        line_end.setX(maxX);
                        view.setX(mx);
                    } else {
                        view.setX(mx);
                    }
                    if (onTimeChangeListener != null) {
                        onTimeChangeListener.call((maxX - mx) * video.getDuration() / (rvW - lineW));
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    break;
                case MotionEvent.ACTION_CANCEL:
                    break;
            }
            view.invalidate();
            return true;
        }
    };
    //开头线的进度
    public float getStartPercent() {
        if (line_start != null && recyclerView != null) {
            return (line_start.getX() - firstStartX) / (rvW - lineW);
        }
        return 0;
    }

    private float firstStartX;//初始时开头的x位置
    private float firstEndX;//初始时结尾的x位置
    private int lineW;//开头与结尾线的宽度
    private int rvW;//图片列表的长度，减去lineW后==总进度的长度

    //结尾线的进度
    public float getEndPercent() {
        if (line_end != null && recyclerView != null) {
            return 1.0f - ((firstStartX + rvW - lineW - line_end.getX()) / (rvW - lineW));
        }
        return 0;
    }

    //总的进度
    public float getPercent() {
        if (line_end != null && recyclerView != null) {
            return (line_end.getX() - line_start.getX()) / (rvW - lineW);
        }
        return 0;
    }

    public String getLineInfo() {
        return String.format(Locale.CHINA, "firstStartX = %f, firstEndX = %f, startX = %f, endX = %f, lineW = %d, rvW = %d, startPercent = %f, endPercent = %f, percent = %f", firstStartX, firstEndX, line_start.getX(), line_end.getX(), line_end.getWidth(), recyclerView.getWidth(), getStartPercent(), getEndPercent(), getPercent());
    }

    private Video video;

    /**
     * 显示视频帧图片列表
     *
     * @param data 视频数据，包括地址与时长，宽高等
     * @return
     */
    public VideoFramesView initVideo(Video data) {
        if (data == null) {
            LogUtil.println(VideoFramesView.class.getSimpleName(), "showList", "error", "data is null");
            return this;
        }
        if (data.getFilePath() == null) {
            LogUtil.println(VideoFramesView.class.getSimpleName(), "showList", "error", "videoPath is null");
            return this;
        }
        File videoFile = new File(data.getFilePath());
        if (!videoFile.exists()) {
            LogUtil.println(VideoFramesView.class.getSimpleName(), "showList", "error", "videoFile not exists");
        }
        if (!videoFile.canRead()) {
            LogUtil.println(VideoFramesView.class.getSimpleName(), "showList", "error", "videoFile cant read");
        }
        if (data.getDuration() < 1) {
            LogUtil.println(VideoFramesView.class.getSimpleName(), "showList", "error", "duration < 1");
        }
        this.video = data;
        return this;
    }

//    private List<Bitmap> bitmapList = new ArrayList<>();
//
//    /**
//     * 显示视频帧图片列表
//     */
//    public VideoFramesView showVideoList1(final Activity activity) {
//        final int size = 10;
//        long duration = video.getDuration();
//        final long per = duration * 1000L / size;
//        int max = 20;
//        int width = max, height = max;
//        if (video.getWidth() > video.getHeight()) {
//            width = max * video.getWidth() / video.getHeight();
//        } else {
//            height = max * video.getHeight() / video.getWidth();
//        }
//        for (int i = 0; i < size; i++) {
//            final int finalWidth = width;
//            final int finalHeight = height;
//            final int finalI = i;
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    Bitmap bitmap = VideoUtil.getVideoFrameBitmap(video, finalI * per, finalWidth, finalHeight);
//                    bitmapList.add(bitmap);
//                    activity.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (recyclerView.getAdapter() != null)
//                                recyclerView.getAdapter().notifyDataSetChanged();
//                        }
//                    });
//                }
//            }).start();
//        }
//        recyclerView.setLayoutManager(new GridLayoutManager(activity.getApplicationContext(), size));
//        BaseQuickAdapter<Bitmap, BaseViewHolder> baseQuickAdapter = new BaseQuickAdapter<Bitmap, BaseViewHolder>(R.layout.item_iv_mh, bitmapList) {
//            @Override
//            protected void convert(BaseViewHolder helper, Bitmap item) {
//                ImageView imageView = helper.getView(R.id.item_iv);
//                imageView.setImageBitmap(item);
//            }
//        };
//        recyclerView.setAdapter(baseQuickAdapter);
//
//        return this;
//    }
//
//    /**
//     * 显示视频帧图片列表
//     */
//    public VideoFramesView showVideoList2(final Activity activity) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                final int size = 10;
//                final List<Bitmap> bitmapList = VideoUtil.getVideoFrameBitmapList(video, size);
//                activity.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        recyclerView.setLayoutManager(new GridLayoutManager(activity.getApplicationContext(), size));
//                        BaseQuickAdapter<Bitmap, BaseViewHolder> baseQuickAdapter = new BaseQuickAdapter<Bitmap, BaseViewHolder>(R.layout.item_iv_mh, bitmapList) {
//                            @Override
//                            protected void convert(BaseViewHolder helper, Bitmap item) {
//                                ImageView imageView = helper.getView(R.id.item_iv);
//                                imageView.setImageBitmap(item);
//                            }
//                        };
//                        recyclerView.setAdapter(baseQuickAdapter);
//                    }
//                });
//
//            }
//        }).start();
//
//        return this;
//    }
//
    /**
     * 显示视频帧图片列表
     */
    public VideoFramesView showVideoList1(final Activity activity) {
        List<VideoFrame> videoFrameList = new ArrayList<>();
        final int size = 10;
        long duration = video.getDuration();
        final long per = duration * 1000L / size;
        int max = 20;
        int width = max, height = max;
        if (video.getWidth() > video.getHeight()) {
            width = max * video.getWidth() / video.getHeight();
        } else {
            height = max * video.getHeight() / video.getWidth();
        }
        String path = video.getFilePath();
        for (int i = 0; i < size; i++) {
            videoFrameList.add(new VideoFrame().setVideoPath(path).setAtTime(i * per).setWidth(width).setHeight(height));
        }
        recyclerView.setLayoutManager(new GridLayoutManager(activity.getApplicationContext(), size));
        BaseQuickAdapter<VideoFrame, BaseViewHolder> baseQuickAdapter = new BaseQuickAdapter<VideoFrame, BaseViewHolder>(R.layout.media_item_iv_mh, videoFrameList) {
            @Override
            protected void convert(BaseViewHolder helper, VideoFrame item) {
                ImageView imageView = helper.getView(R.id.media_item_iv);
                Glide.with(activity.getApplicationContext()).load(item.getVideoPath())
                        .apply(RequestOptions.frameOf(item.getAtTime()).set(VideoBitmapDecoder.FRAME_OPTION, MediaMetadataRetriever.OPTION_CLOSEST).transform(new VideoFrameTransform(item, false)))
                        .into(imageView);
            }
        };
        recyclerView.setAdapter(baseQuickAdapter);

        return this;
    }
    /**
     * 显示视频帧图片列表
     */
    public VideoFramesView showVideoList(final Activity activity) {
        if(TextUtils.equals(android.os.Build.CPU_ABI, "x86")) {//x86不兼容，不能在模拟器中连续调用FFmpegMediaMetadataRetriever
            return showVideoList1(activity);
        } else {
            return showVideoList1(activity);
        }
    }
    /**
     * 显示视频帧图片列表
     */
    public VideoFramesView showVideoList2(final Activity activity) {
        List<VideoFrame> videoFrameList = new ArrayList<>();
        final int size = 10;
        long duration = video.getDuration();
        final long per = duration * 1000L / size;
        String path = video.getFilePath();

        for (int i = 0; i < size; i++) {
            long atTime = i + 1 == size ? (i * per - per / 2) : i * per;//这个框架真的是无语了，正常分最后的图片总是获取不到
            LogUtil.println(VideoFramesView.class.getSimpleName(), "showVideoList2", duration, i, per, atTime);
            videoFrameList.add(new VideoFrame().setVideoPath(path).setAtTime(atTime)
                    .setWidth(video.getWidth()).setHeight(video.getHeight())
                    .setOrientation(video.getOrientation())
            );
        }
        recyclerView.setLayoutManager(new GridLayoutManager(activity.getApplicationContext(), size));
        BaseQuickAdapter<VideoFrame, BaseViewHolder> baseQuickAdapter = new BaseQuickAdapter<VideoFrame, BaseViewHolder>(R.layout.media_item_iv_mh, videoFrameList) {
            @Override
            protected void convert(BaseViewHolder helper, VideoFrame item) {
                ImageView imageView = helper.getView(R.id.media_item_iv);
                Glide.with(activity.getApplicationContext()).load(ViewUtil.getNetImgByName("alter_original"))
                        .apply(new RequestOptions().transform(new VideoFrameTransform(item)))
                        .into(imageView);
            }
        };
        recyclerView.setAdapter(baseQuickAdapter);

        return this;
    }

    private Action1<Float> onTimeChangeListener;

    public void setOnTimeChangeListener(Action1<Float> action1) {
        onTimeChangeListener = action1;
        postDelayed(new Runnable() {
            @Override
            public void run() {
                firstStartX = line_start.getX();
                firstEndX = line_end.getX();
                lineW = line_start.getWidth();
                rvW = recyclerView.getWidth();
                long duration = video.getDuration();
                if (maxVideoDuration > 0) {
                    if (duration > maxVideoDuration) {
                        firstEndX = firstStartX + ((maxVideoDuration * 1.0f / duration) * (rvW - lineW));
                        line_end.setX(firstEndX);
                    }
                }
                onTimeChangeListener.call((float) duration);
            }
        }, 100);
    }

    //开始的时间,单位秒
    public long getStartPoint() {
        return (long) (getStartPercent() * video.getDuration());
    }

    //总共的时长,单位秒
    public long getLineDuration() {
        return (long) (getPercent() * video.getDuration());
    }

    //结束的时间,单位秒
    public long getEndPoint() {
        return (long) (getEndPercent() * video.getDuration());
    }

    //最大剪切视频时长
    private long maxVideoDuration;

    public VideoFramesView setMaxDuration(long maxVideoDuration) {
        this.maxVideoDuration = maxVideoDuration;
        return this;
    }

    public void onDestroy() {
        if (recyclerView != null && recyclerView.getAdapter() instanceof BaseQuickAdapter) {
            for (int i = 0; i < recyclerView.getAdapter().getItemCount(); i++) {
                Object object = ((BaseQuickAdapter) recyclerView.getAdapter()).getItem(i);
                if (object instanceof Bitmap) {
                    try {
                        ((Bitmap) object).recycle();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
