package com.efounder.chat.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;

import com.efounder.chat.R;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.LoopingMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.utilcode.util.ToastUtils;

import java.io.File;

public class VideoReviewActivity extends Activity implements View.OnClickListener {
    static String sdDir = null;
    private static final String TAG = "VideoReviewActivity";

    static {

        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory().toString();//获取根目录
        } else {
            sdDir = Environment.getRootDirectory().toString();
        }
    }

    private SimpleExoPlayer player;
    private TrackSelector trackSelector;
    private SimpleExoPlayerView simpleExoPlayerView;
    private String videoFilePath;
    private String videoTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_review);
        Intent intent = getIntent();
        videoFilePath = intent.getStringExtra("videoFilePath");
        videoTime = intent.getStringExtra("videoTime");
        initFindView();
        initData();
    }

    private void initFindView() {
        simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player_view);
        findViewById(R.id.confirmIv).setOnClickListener(this);
        findViewById(R.id.cancleIv).setOnClickListener(this);
    }

    private void initData() {
        String filepath = videoFilePath;
        if (new File(filepath).exists()) {
            initPlayer(filepath);
        } else {
            ToastUtils.showShort(R.string.wrchatview_video_address_error);
        }
    }


    private void initPlayer(String filepath) {
        // 1. Create a default TrackSelector
        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
        trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);

        player = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
        simpleExoPlayerView.setPlayer(player);

// Produces DataSource instances through which media data is loaded.
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this,
                Util.getUserAgent(this, "OSP Application"), bandwidthMeter);
// Produces Extractor instances for parsing the media data.
        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
// This is the MediaSource representing the media to be played.
//        String filepath = sdDir + "/OSPMobileLiveApp" + "/2967/chat/chatvideo/1499307856384.mp4";
//        String filepath = sdDir+"/OSPMobileLiveApp"+"/2967/chat/chatvideo/1499312193963.mov";
        Uri mp4VideoUri = Uri.parse(filepath);
        final MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri,
                dataSourceFactory, extractorsFactory, null, null);
        /**
         * 默认循环2147483647
         */
        LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);
        player.prepare(loopingSource, true, true);
        View chiild0 = simpleExoPlayerView.getChildAt(1);
        if (chiild0 != null) {
            View childAt = ((ViewGroup) chiild0).getChildAt(0);
            if (childAt != null) {
                childAt.setVisibility(View.GONE);
            }

        }
        View child0 = simpleExoPlayerView.getChildAt(0);
        if (child0 != null) {
            child0.setBackgroundColor(Color.parseColor("#000000"));
        }
        player.setPlayWhenReady(true);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (Util.SDK_INT <= 23) {
            releasePlayer();
        }
    }

    private void releasePlayer() {
        if (player != null) {
            player.release();
            player = null;
            trackSelector = null;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (Util.SDK_INT > 23) {
            releasePlayer();
        }
    }

    public static void open(String videoFilePath, String videoTime, int requestCode, Activity context) {

        Intent intent = new Intent(context, VideoReviewActivity.class);
        intent.putExtra("videoFilePath", videoFilePath);
        intent.putExtra("videoTime", videoTime);
        context.startActivityForResult(intent, requestCode);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.cancleIv) {
            setResult(RESULT_CANCELED, null);
            finish();
        } else if (id == R.id.confirmIv) {
            Intent intent = new Intent();
            intent.putExtra("path", videoFilePath);
            intent.putExtra("videoTime", videoTime);
            setResult(RESULT_OK, intent);
            finish();
        }
    }
}
