package com.anren.omplayer;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.res.TypedArray;
import android.graphics.Matrix;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RawRes;
import android.util.AttributeSet;
import android.view.Surface;
import android.view.TextureView;

import com.tencent.rtmp.TXVodPlayConfig;
import com.tencent.rtmp.TXVodPlayer;
import com.yqritc.scalablevideoview.ScalableType;
import com.yqritc.scalablevideoview.ScaleManager;
import com.yqritc.scalablevideoview.Size;

import java.io.FileDescriptor;
import java.io.IOException;
import java.util.Map;

/**
 * Created by lcg on 2017/6/23.
 */

public class OMScalableVideoViewTc extends TextureView implements TextureView.SurfaceTextureListener,
        MediaPlayer.OnVideoSizeChangedListener {

    protected TXVodPlayer mMediaPlayer;
    protected ScalableType mScalableType = ScalableType.NONE;
    private String mDataSource = null;

    public OMScalableVideoViewTc(Context context) {
        this(context, null);
    }

    public OMScalableVideoViewTc(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public OMScalableVideoViewTc(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        if (attrs == null) {
            return;
        }

        TypedArray a = context.obtainStyledAttributes(attrs, com.yqritc.scalablevideoview.R.styleable.scaleStyle, 0, 0);
        if (a == null) {
            return;
        }

        int scaleType = a.getInt(com.yqritc.scalablevideoview.R.styleable.scaleStyle_scalableType, ScalableType.NONE.ordinal());
        a.recycle();
        mScalableType = ScalableType.values()[scaleType];
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
        Surface surface = new Surface(surfaceTexture);
        if (mMediaPlayer != null) {
            mMediaPlayer.setSurface(surface);
        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    @Override
    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        scaleVideoSize(width, height);
    }

    private void scaleVideoSize(int videoWidth, int videoHeight) {
        if (videoWidth == 0 || videoHeight == 0) {
            return;
        }

        Size viewSize = new Size(getWidth(), getHeight());
        Size videoSize = new Size(videoWidth, videoHeight);
        ScaleManager scaleManager = new ScaleManager(viewSize, videoSize);
        Matrix matrix = scaleManager.getScaleMatrix(mScalableType);
        if (matrix != null) {
            setTransform(matrix);
        }
    }

//    private void initializeMediaPlayer(@Nullable Map<String, String> headers) {
//        if (mMediaPlayer == null) {
//            mMediaPlayer = new TXVodPlayer(this.getContext());
//
//            TXVodPlayConfig mVodPlayConfig = new TXVodPlayConfig();
//            mVodPlayConfig.setHeaders(headers);
//            mMediaPlayer.setConfig(mVodPlayConfig);
////            mMediaPlayer.setOnVideoSizeChangedListener(this);
//            setSurfaceTextureListener(this);
//            mMediaPlayer.setVodListener(mMediaPlayer);
//        } else {
//            mMediaPlayer.seek(0);
////            mMediaPlayer.reset();
//        }
//    }

//    public void setRawData(@RawRes int id) throws IOException {
//        AssetFileDescriptor afd = getResources().openRawResourceFd(id);
//        setDataSource(afd);
//    }

//    public void setAssetData(@NonNull String assetName) throws IOException {
//        AssetManager manager = getContext().getAssets();
//        AssetFileDescriptor afd = manager.openFd(assetName);
//        setDataSource(afd);
//    }

//    private void setDataSource(@NonNull AssetFileDescriptor afd) throws IOException {
//        setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
//        afd.close();
//    }

    public void setDataSource(@NonNull String path) throws IOException {
        mDataSource = path;
//        initializeMediaPlayer(null);
//        mMediaPlayer.startPlay(path);
    }

    public void setDataSource(@NonNull Context context, @NonNull Uri uri,
                              @Nullable Map<String, String> headers) throws IOException {
        mDataSource = uri.toString();
//        initializeMediaPlayer(headers);
//        mMediaPlayer.setDataSource(context, uri, headers);
//        mMediaPlayer.startPlay(mDataSource);
    }

    public void setDataSource(@NonNull Context context, @NonNull Uri uri) throws IOException {
        mDataSource = uri.toString();
//        initializeMediaPlayer(null);
//        mMediaPlayer.startPlay(mDataSource);
    }

//    public void setDataSource(@NonNull FileDescriptor fd, long offset, long length)
//            throws IOException {
////        mDataSource = fd.toString();
////        initializeMediaPlayer();
////        mMediaPlayer.setDataSource(fd, offset, length);
//    }

//    public void setDataSource(@NonNull FileDescriptor fd) throws IOException {
//        initializeMediaPlayer();
//        mMediaPlayer.setDataSource(fd);
//    }

    public void setScalableType(ScalableType scalableType) {
        mScalableType = scalableType;
        scaleVideoSize(getVideoWidth(), getVideoHeight());
    }

    public void prepare(@Nullable MediaPlayer.OnPreparedListener listener)
            throws IOException, IllegalStateException {
//        mMediaPlayer.setOnPreparedListener(listener);
//        mMediaPlayer.prepare();
    }

    public void prepareAsync(@Nullable MediaPlayer.OnPreparedListener listener)
            throws IllegalStateException {
//        mMediaPlayer.setOnPreparedListener(listener);
//        mMediaPlayer.prepareAsync();
    }

    public void prepare() throws IOException, IllegalStateException {
        prepare(null);
    }

    public void prepareAsync() throws IllegalStateException {
        prepareAsync(null);
    }

    public int getCurrentPosition() {
        return (int) mMediaPlayer.getCurrentPlaybackTime();
    }

    public int getDuration() {
        return (int)mMediaPlayer.getDuration();
    }

    public int getVideoHeight() {
        return mMediaPlayer.getHeight();
    }

    public int getVideoWidth() {
        return mMediaPlayer.getWidth();
    }

    public boolean isLooping() {
        return mMediaPlayer.isLoop();
    }

    public boolean isPlaying() {
        return mMediaPlayer.isPlaying();
    }

    public void pause() {
        mMediaPlayer.pause();
    }

    public void seekTo(int msec) {
        mMediaPlayer.seek(msec / 1000);
    }

    public void setLooping(boolean looping) {
        mMediaPlayer.setLoop(looping);
    }
    public void setRate(float rate) {
        mMediaPlayer.setRate(rate);
    }

//    public void setVolume(float leftVolume, float rightVolume) {
//        mMediaPlayer.s(leftVolume, rightVolume);
//    }

    public void start() {
        if (mMediaPlayer.getDuration() > 0.0) {
            mMediaPlayer.resume();
        } else {
            mMediaPlayer.startPlay(mDataSource);
        }
    }

    public void stop() {
        mMediaPlayer.stopPlay(false);
    }

    public void release() {
        mMediaPlayer.stopPlay(true);
//        mMediaPlayer.reset();
//        mMediaPlayer.release();
    }

    public void setMediaPlayer(TXVodPlayer mediaPlayer) {
        mMediaPlayer = mediaPlayer;
    }

    public TXVodPlayer getMediaPlayer(){
        return mMediaPlayer;
    }
}
