package com.excelliance.open.video;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.excelliance.open.BwbxUI;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

public class VideoView extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = "VideoView";
    private SurfaceHolder holder;
    private MediaPlayer player = null;
    private Context mContext;
    private Resources mainRes = null;
    private int position;
    private AssetFileDescriptor fileDescriptor = null;

    private static final String VIDEO_NAME = "lebian_background.mp4";
    public VideoView(Context context) {
        this(context,null);
    }

    public VideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        holder = getHolder();
        holder.addCallback(this);

        player = new MediaPlayer();

        mainRes = BwbxUI.getApkResources(context);

    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try{
            init();
            play();
            player.seekTo(position);
            position = 0;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void init(){
        try {
            player.reset();
            fileDescriptor = mainRes.getAssets().openFd(VIDEO_NAME);
            player.setDataSource(fileDescriptor.getFileDescriptor(),
                    fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            player.setDisplay(holder);
            player.prepare();
            int sMode = BwbxUI.getGlobalInt(mContext, "SCALE_MODE_IN_NEXTCHAPTER", 0);
            if (sMode == 0) {
                player.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
            }
            player.setLooping(true);
            fileDescriptor.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void play(){
        player.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }

    public void onStop(){
        if(player.isPlaying()){
            position = player.getCurrentPosition();
            player.pause();
        }
    }

    public void onDestroy(){
        if(player.isPlaying()){
            player.stop();
            player.release();
        }
    }
}
