package com.sobot.album.app.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.sobot.album.AlbumFile;
import com.sobot.album.R;
import com.sobot.album.SobotAlbum;
import com.sobot.utils.SobotStringUtils;

import java.io.IOException;

public class VideoFragment extends Fragment {
    private View mRootView;
    private VideoView mVideoView;
    private ImageView mIvPreview;
    private ImageView mIvPlay;
    private AlbumFile mAlbum;
    private MediaPlayer mMediaPlayer;
    private Bitmap firstFrame;

    public static VideoFragment getInstance(AlbumFile mAlbum) {
        VideoFragment fragment = new VideoFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable("mAlbum", mAlbum);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setArguments(@Nullable Bundle bundle) {
        super.setArguments(bundle);
        if (bundle != null) {
            mAlbum = bundle.getParcelable("mAlbum");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_video_item, container, false);
        initView();
        return mRootView;
    }

    private void initView() {
        mVideoView = mRootView.findViewById(R.id.fragment_preview_video);
        mIvPreview = mRootView.findViewById(R.id.fragment_preview_first_frame);
        mIvPlay = mRootView.findViewById(R.id.fragment_preview_play_img);
        if (mAlbum != null) {
            //设置预览图
//            setFirstFrameDrawable(getContext(),mAlbum.getUri());
            if(SobotStringUtils.isNoEmpty(mAlbum.getThumbPath())) {
                SobotAlbum.getAlbumConfig().getAlbumLoader().load(mIvPreview, mAlbum);
            }else{
                //获取封面图
                Bitmap bitmap = null;
                // 首先创建一个MediaMetadataRetriever
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                try {
                    retriever.setDataSource(getContext(),mAlbum.getUri()); // setDataSource
                    bitmap = retriever.getFrameAtTime(-1); // 获取封面
                    // 此处有两种方式获取封面，一种是getFrameAtTime，　一种是getImageAtIndex
                    // 这两个的区别是一个是通过时间戳解析封面，另一个是通过index解析封面
                } catch (IllegalArgumentException ex) {
                    // Assume this is a corrupt video file
                } catch (RuntimeException ex) {
                    // Assume this is a corrupt video file.
                } finally {
                    try {
                        retriever.release();
                    } catch (Exception ex) {
                        // Ignore failures while cleaning up.
                    }
                }
                if(null!=bitmap){
                    mIvPreview.setImageBitmap(bitmap);
                }
            }

            //设置视频
            mVideoView.setVideoURI(mAlbum.getUri());
            mIvPlay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mIvPreview.setVisibility(View.GONE);
                    mVideoView.setVisibility(View.VISIBLE);
                    mVideoView.start();
                    mIvPlay.setVisibility(View.GONE);
                }
            });
            mVideoView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mVideoView.getVisibility() == View.VISIBLE) {
                        mVideoView.pause();
                        mIvPlay.setVisibility(View.VISIBLE);
                    } else {
                        mIvPreview.setVisibility(View.GONE);
                        mVideoView.setVisibility(View.VISIBLE);
                        mVideoView.start();
                        mIvPlay.setVisibility(View.GONE);
                    }
                }
            });
            try {

                Surface surface = mVideoView.getHolder().getSurface();
                //surface没准备好时不执行播放
                if (!surface.isValid()) {
                    return;
                }
                if (mMediaPlayer == null) {
                    mMediaPlayer = new MediaPlayer();
                } else {
                    mMediaPlayer.reset();
                }
                mMediaPlayer.setDataSource(getContext(), mAlbum.getUri());
                mMediaPlayer.setSurface(surface);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mMediaPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT);
                }
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer
                        .OnVideoSizeChangedListener() {
                    @Override
                    public void
                    onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                        updateVideoViewSize(mMediaPlayer.getVideoWidth(), mMediaPlayer
                                .getVideoHeight());
                    }
                });
                mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        updateVideoViewSize(mp.getVideoWidth(), mp
                                .getVideoHeight());
//                        startVideo();
                    }
                });
                mMediaPlayer.setLooping(false);
                mMediaPlayer.prepareAsync();
                MediaController mediaController = new MediaController(getContext());
                mVideoView.setMediaController(mediaController);
                mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        mIvPlay.setVisibility(View.VISIBLE);
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();

            }
        }

    }

    private void setFirstFrameDrawable(Context context, final Uri url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                mmr.setDataSource(context, url);
                firstFrame = mmr.getFrameAtTime();
                mHandler.sendEmptyMessage(0);
            }
        }).start();
    }

    private void updateVideoViewSize(float videoWidth, float videoHeight) {
        FrameLayout.LayoutParams videoViewParam;
        int height = (int) ((videoHeight / videoWidth) * mVideoView.getWidth());
        videoViewParam = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height);
        videoViewParam.gravity = Gravity.CENTER;
        mVideoView.setLayoutParams(videoViewParam);
    }

    @Override
    public void onPause() {
        if (mVideoView.isPlaying()) {
            mVideoView.pause();
        }
        mIvPlay.setVisibility(View.VISIBLE);
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        mVideoView.suspend();
        super.onDestroyView();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mIvPreview.setVisibility(View.VISIBLE);
            mIvPreview.setImageBitmap(firstFrame);
        }
    };
}
