package com.xixun.xixunplayer;

import android.content.Context;
import android.media.MediaPlayer;
import android.view.Choreographer;
import android.widget.VideoView;

public class EleVideo extends VideoView implements Choreographer.FrameCallback {

    float vol = 1;

    public EleVideo(String path, Context context) {
        super(context);
        setVideoPath(path);
        setOnPreparedListener((MediaPlayer player)->{
            player.setLooping(true);
            if(! isShown()) {
                player.seekTo(0);
                player.pause();
            }
            if(vol!=1) player.setVolume(vol, vol);
            setOnPreparedListener(null);
        });
        setOnErrorListener((MediaPlayer mp, int what, int extra)->{
            Util.makeText(getContext(), "Media Error: "+getErrorName(what)+". "+getErrorName(extra)).show();
            return true;
        });
        start();
        choreographer.postFrameCallback(this);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
    }

    @Override
    public void onVisibilityAggregated(boolean isVisible) {
        super.onVisibilityAggregated(isVisible);
        if(isVisible) {
            if(! isPlaying()) start();
        } else {
            seekTo(0);
            pause();
            choreographer.postFrameCallback(this);
        }
    }

    Choreographer choreographer = Choreographer.getInstance();
    @Override
    public void doFrame(long frameTimeNanos) {
        if(isShown()) return;
        if(isPlaying()) {
            seekTo(0);
            pause();
            System.out.println("pause in doFrame()");
        }
        choreographer.postFrameCallback(this);
    }

    static String getErrorName(int code) {
        if(code==MediaPlayer.MEDIA_ERROR_UNKNOWN) return "UNKNOWN";
        if(code==MediaPlayer.MEDIA_ERROR_SERVER_DIED) return "SERVER_DIED";
        if(code==MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) return "NOT_VALID_FOR_PROGRESSIVE_PLAYBACK";
        if(code==MediaPlayer.MEDIA_ERROR_IO) return "IO";
        if(code==MediaPlayer.MEDIA_ERROR_MALFORMED) return "MALFORMED";
        if(code==MediaPlayer.MEDIA_ERROR_UNSUPPORTED) return "UNSUPPORTED";
        if(code==MediaPlayer.MEDIA_ERROR_TIMED_OUT) return "TIMED_OUT";
        if(code==-2147483648) return "SYSTEM";
        return "Unknown ("+code+")";
    }
}