package com.kfzs.cfyl.media.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.VideoView;

import com.alibaba.fastjson.JSONObject;
import com.kfzs.cfyl.media.BaseContainerActivity;
import com.kfzs.cfyl.media.R;
import com.kfzs.cfyl.media.api.IdChooser;
import com.kfzs.cfyl.media.customview.VideoFramesView;
import com.kfzs.cfyl.media.fragment.FgtDiscoveryTopic;
import com.kfzs.cfyl.media.util.G;
import com.kfzs.cfyl.media.util.KeyEventUtil;
import com.kfzs.cfyl.media.util.ListUtil;
import com.kfzs.cfyl.media.util.VideoUtil;
import com.kfzs.cfyl.media.util.ViewUtil;
import com.kfzs.cfyl.share_library.util.LogUtil;
import com.sheep.gamegroup.model.entity.Video;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Locale;

import rx.functions.Action1;

/**
 * Created by realicing on 2018/11/9.
 * realicing@sina.com
 * 添加话题并剪切视频
 */
public class ActCutVideo extends BaseContainerActivity implements MediaPlayer.OnInfoListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener, IdChooser {

    VideoView videoView;
    View video_loading;
    VideoFramesView videoFramesView;
    TextView edit_video_time_tv;

    TextView edit_video_topic_tv;
    TextView edit_video_sure_tv;
    View frame_container;

    @Override
    protected int getLayoutId() {
        return R.layout.media_act_cut_video;
    }


    public static final long MAX_VIDEO_DURATION = 15_000L;//视频最大时长，超过需要剪切
    private Video data;

    private ArrayList<String> arrayList;//主题列表


    @Override
    protected Fragment initFragment() {
        return new FgtDiscoveryTopic();
    }
    @Override
    public void initView() {
        super.initView();

        Intent intent = getIntent();
        arrayList = intent.getStringArrayListExtra(ArrayList.class.getSimpleName());
        if (arrayList != null && fragment instanceof FgtDiscoveryTopic)
            ((FgtDiscoveryTopic) fragment).loadData(arrayList);
        data = JSONObject.parseObject(intent.getStringExtra(String.class.getSimpleName()), Video.class);
        Uri uri = Uri.parse(data.getFilePath());

        videoView = findViewById(R.id.media_videoView);
        video_loading = findViewById(R.id.media_video_loading);
        videoFramesView = findViewById(R.id.media_videoFramesView);
        edit_video_time_tv = findViewById(R.id.media_edit_video_time_tv);
        edit_video_topic_tv = findViewById(R.id.media_edit_video_topic_tv);
        edit_video_sure_tv = findViewById(R.id.media_edit_video_sure_tv);
        frame_container = findViewById(R.id.media_frame_container);

        videoView.setOnInfoListener(this);
        videoView.setOnPreparedListener(this);
        videoView.setOnErrorListener(this);
        videoView.setOnCompletionListener(this);
//        videoView.setMediaController(new MediaController(this));
        videoView.setVideoURI(uri);
        videoFramesView.initVideo(data).setMaxDuration(MAX_VIDEO_DURATION).showVideoList(this).setOnTimeChangeListener(new Action1<Float>() {
            @Override
            public void call(Float duration) {
                if (duration == null)
                    return;
                if (videoFramesView.getVisibility() == View.VISIBLE)
                    checkDuration(duration.longValue());
                edit_video_time_tv.setText(getString(R.string.media_has_choose_x_second, new DecimalFormat("#.#").format(duration / 1000.0f)));
//                edit_video_time_tv.append("\t");
//                edit_video_time_tv.append(String.valueOf(duration));
//                edit_video_time_tv.append("\t");
//                edit_video_time_tv.append(String.valueOf(data.getDuration()));
//                edit_video_time_tv.append("\t");
//                edit_video_time_tv.append(String.format(Locale.CHINA, "%.1f秒-%.1f秒", videoFramesView.getStartPoint() / 1000.0f, videoFramesView.getEndPoint() / 1000.0f));
//                edit_video_time_tv.append("\t");
//                edit_video_time_tv.append(videoFramesView.getLineInfo());
            }
        });
        //隐藏视频剪切相关view
        edit_video_time_tv.setVisibility(View.INVISIBLE);
        videoFramesView.setVisibility(View.INVISIBLE);
    }

    private static final String TAG = ActCutVideo.class.getSimpleName();

    //检查有没有设置剪切视频的时长
    private void checkDuration(long duration) {
        LogUtil.println(TAG, data.getDuration(), duration);
        if ((data.getDuration() - duration) >= 500) {
            edit_video_sure_tv.setText(BTN_TEXT_CUT);
        } else {
            edit_video_sure_tv.setText(BTN_TEXT_FINISH);
        }
    }


    //播放或者暂停
    private void playOrPause() {
        if (videoView.isPlaying()) {
            pause();
        } else {
            play();
        }
    }

    //播放
    private void play() {
        if (videoView == null) {
            return;
        }
        videoView.start();
    }

    //暂停
    private void pause() {
        if (videoView == null) {
            return;
        }
        videoView.pause();
    }

    //销毁
    private void destroy() {
        if (videoView == null) {
            return;
        }
        videoView.stopPlayback();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isPauseByUser)
            play();
    }

    //是否是用户手机暂停
    private boolean isPauseByUser;

    @Override
    protected void onPause() {
        super.onPause();
        if (videoView != null && videoView.isPlaying())
            isPauseByUser = false;
        if (video_loading != null)
            video_loading.setVisibility(View.VISIBLE);
        pause();
    }

    @Override
    protected void onDestroy() {
        destroy();
        if (videoFramesView != null)
            videoFramesView.onDestroy();
        super.onDestroy();
    }

    @Override
    public boolean onInfo(MediaPlayer mediaPlayer, int what, int extra) {
        LogUtil.println("ActPlayVideo", "onInfo what = " + what + " extra = " + extra);
        if (!mediaPlayer.isLooping())
            mediaPlayer.setLooping(true);
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                LogUtil.println("ActPlayVideo", "onInfo", "正在缓冲");
                if (video_loading != null)
                    video_loading.setVisibility(View.VISIBLE);
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
            case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                LogUtil.println("ActPlayVideo", "onInfo", "缓冲完成");
                //缓存完成，继续播放
                if (video_loading != null)
                    video_loading.setVisibility(View.GONE);
                break;
        }
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        LogUtil.println("ActPlayVideo", "onPrepared");
        if (video_loading != null)
            video_loading.setVisibility(View.GONE);
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
        LogUtil.println("ActPlayVideo", "onInfo what = " + what + " extra = " + extra);
        return false;
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        LogUtil.println("ActPlayVideo", "onCompletion");
    }

    //点击话题进行切换
    public void onClickTopic(View view) {
        ViewUtil.toggleVisibility(frame_container);
        ViewUtil.setText(edit_video_sure_tv, BTN_TEXT_NEXT);
        if (ViewUtil.isVisible(frame_container)) {
            ViewUtil.setVisibility2(edit_video_time_tv, false);
            ViewUtil.setVisibility2(videoFramesView, false);
        }
    }

    //点击返回
    public void onClickBackImg(View view) {
        KeyEventUtil.sendKeyDownUp(KeyEvent.KEYCODE_BACK);
    }

    private static final String BTN_TEXT_NEXT = "下一步";
    private static final String BTN_TEXT_CUT = "剪切";
    private static final String BTN_TEXT_FINISH = "完成";

    //点击确定
    public void onClickSure(View view) {
        String btnText = ((TextView) view).getText().toString();
        switch (btnText) {
            case BTN_TEXT_NEXT:
                showCut();
                break;
            case BTN_TEXT_CUT:
                tryCut();
                break;
            case BTN_TEXT_FINISH:
                finishCut();
                break;
        }
    }

    private void finishCut() {//完成剪切并返回数据
        Intent intent = new Intent();
        intent.putExtra(Video.class.getSimpleName(), data);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void tryCut() {//其次完成编辑
        showProgress().getTextView().setText("剪切视频中");
        VideoUtil.tryCutVideo(data.getFilePath(), videoFramesView.getStartPoint() * 1000, videoFramesView.getLineDuration() * 1000, new Action1<Object>() {
            @Override
            public void call(final Object result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result instanceof Video) {
                            Video video = (Video) result;
                            data.setFilePath(video.getFilePath());
                            data.setWidth(video.getWidth());
                            data.setHeight(video.getHeight());
                            data.setDuration(video.getDuration());
                            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + video.getFilePath())));
                            hideProgress();
                            G.showToast(getApplicationContext(), "剪切完成");
                            finishCut();
                        } else if (result instanceof Throwable) {
                            hideProgress();
                            G.showToast(getApplicationContext(), ((Throwable) result).getMessage());
                        }
                    }
                });
            }
        });
    }

    private void showCut() {//首先隐藏话题列表
        ViewUtil.setVisibility(frame_container, false);
        ViewUtil.setVisibility2(edit_video_time_tv, true);
        ViewUtil.setVisibility2(videoFramesView, true);
        checkDuration(videoFramesView.getLineDuration());
    }

    @Override
    public void onSelectId(int id) {
        String item = ListUtil.getItem(arrayList, id);
        if (item != null) {
            data.setTopicIndex(id);
            ViewUtil.setText(edit_video_topic_tv, "#%s#", item);
        }
    }
}
