package com.jimind.sportdemo;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.jimind.sportdemo.adapter.SectionAdapter;
import com.jimind.sportdemo.api.ApiManager;
import com.jimind.sportdemo.base.BaseActivity;
import com.jimind.sportdemo.base.BaseObserver;
import com.jimind.sportdemo.base.ResponseResult;
import com.jimind.sportdemo.bean.Course;
import com.jimind.sportdemo.bean.Section;
import com.jimind.sportdemo.listener.MyClickListener;
import com.jimind.sportdemo.utils.CommonUtils;
import com.jimind.sportdemo.utils.Constant;
import com.jimind.sportdemo.utils.GlideApp;
import com.jimind.sportdemo.utils.TimeFormatUtils;
import com.jimind.sportdemo.view.VerticalSeekBar;

import org.json.JSONException;
import org.json.JSONObject;
import org.videolan.libvlc.IVLCVout;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaPlayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 课程播放
 *
 * @author Any
 */
public class CoursePlayActivity extends BaseActivity
        implements MediaPlayer.EventListener, IVLCVout.Callback,
        SeekBar.OnSeekBarChangeListener, MyClickListener,
        View.OnTouchListener {

    @BindView(R.id.cl_course_play)
    ConstraintLayout clCoursePlay;
    @BindView(R.id.tv_play_title)
    TextView tvPlayTitle;
    @BindView(R.id.tv_total_number)
    TextView tvTotalNumber;
    @BindView(R.id.tv_heart_beat)
    TextView tvHeartBeat;
    @BindView(R.id.tv_step_count)
    TextView tvStepCount;
    @BindView(R.id.tv_strength)
    TextView tvStrength;
    @BindView(R.id.tv_density)
    TextView tvDensity;
    @BindView(R.id.tv_reach_rate)
    TextView tvReachRate;
    @BindView(R.id.video_player)
    SurfaceView mSurfaceView;
    @BindView(R.id.iv_player)
    ImageView ivPhotoPlayer;
    @BindView(R.id.rlv_section)
    RecyclerView rlvSection;
    @BindView(R.id.ib_play)
    ImageButton ibPlay;
    @BindView(R.id.sk_play)
    SeekBar skPlay;
    @BindView(R.id.tv_current_time)
    TextView tvCurrentTime;
    @BindView(R.id.tv_total_time)
    TextView tvTotalTime;
    @BindView(R.id.ib_light)
    ImageButton ibLight;
    @BindView(R.id.ib_voice)
    ImageButton ibVoice;
    @BindView(R.id.ll_course_desc)
    LinearLayout llCourseDesc;
    @BindView(R.id.tv_section_count)
    TextView tvSectionCount;
    @BindView(R.id.tv_section_title)
    TextView tvSectionTitle;
    @BindView(R.id.tv_section_summary)
    TextView tvSectionSummary;
    @BindView(R.id.sk_voice)
    VerticalSeekBar skVoice;
    @BindView(R.id.sk_light)
    VerticalSeekBar skLight;

    private Course mCourse;
    private LibVLC mLibVLC;
    private Disposable mDisposable;
    private MediaPlayer mMediaPlayer;
    private EventManager mEventManager;
    private EventListener mEventListener;
    private SectionAdapter mSectionAdapter;
    private LinearLayoutManager mLinearManager;
    private boolean isPhotoPlaying, isFistInit = true;
    private String mLastSectionId, mJson, mSectionId;
    private List<Section> mResourceList = new ArrayList<>(), mSectionList = new ArrayList<>();
    private int mLocation, mCurrentMills, mResourceDuration, mResourceType, mMaxVolume, mCurrentPosition, mLastPosition, mTotalNumber;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_course_play;
    }

    @Override
    protected void initView() {
        CommonUtils.initTitleBar(this, clCoursePlay);
        Intent intent = this.getIntent();
        mTotalNumber = intent.getIntExtra(Constant.TOTAL_NUMBER, 0);
        mCourse = (Course) intent.getSerializableExtra(Constant.COURSE);
        tvPlayTitle.setText(mCourse.getCourseName());
        tvTotalNumber.setText(String.valueOf(mTotalNumber));

        //初始化recyclerView
        mLinearManager = new LinearLayoutManager(this);
        rlvSection.setLayoutManager(mLinearManager);
        mSectionAdapter = new SectionAdapter(this);
        rlvSection.setAdapter(mSectionAdapter);
        //设置seekBar不能手动拖动
        skPlay.setEnabled(false);
        //设置文字较多时，可以滑动显示
        tvSectionSummary.setMovementMethod(ScrollingMovementMethod.getInstance());

        //初始化视频播放
        mLibVLC = new LibVLC();
        mMediaPlayer = new MediaPlayer(mLibVLC);
        IVLCVout vlcVout = mMediaPlayer.getVLCVout();
        vlcVout.setVideoView(mSurfaceView);
        vlcVout.attachViews();
        vlcVout.addCallback(this);
        mMediaPlayer.setEventListener(this);

        //设置音量
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        mMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        skVoice.setMax(mMaxVolume);
        //设置当前设备静音
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
        skVoice.setOnSeekBarChangeListener(this);
        skVoice.setOnTouchListener(this);

        //设置亮度,系统亮度值范围：0～255，应用窗口亮度范围：0.0f～1.0f。
        skLight.setMax(255);
        try {
            int currentBright = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            skLight.setProgress(currentBright);
        } catch (Exception e) {
            e.printStackTrace();
        }
        skLight.setOnSeekBarChangeListener(this);
        skLight.setOnTouchListener(this);

        //百度语音，唤醒词
        Map<String, Object> params = new HashMap<>();
        params.put(SpeechConstant.WP_WORDS_FILE, "assets:///WakeUp.bin");
        mJson = new JSONObject(params).toString();
    }

    @Override
    protected void initData() {
        getSectionList();
        mEventManager = EventManagerFactory.create(this, "wp");
        mEventListener = new EventListener() {
            @Override
            public void onEvent(String name, String params, byte[] data, int offset, int length) {
                if ("wp.data".equals(name)) {
                    try {
                        JSONObject json = new JSONObject(params);
                        int errorCode = json.getInt("errorCode");
                        if (errorCode == 0) {
                            //唤醒成功
                            String word = json.getString("word");
                            Log.e("com.jimind.sportdemo", "current word = " + word);
                            switch (word) {
                                case Constant.START:
                                    break;
                                case Constant.PLAY:
                                case Constant.PAUSE:
                                    controlPlay();
                                    break;
                                case Constant.RESTART:
                                    click(mCurrentPosition);
                                    break;
                                case Constant.INCREASE_VOLUME:
                                    sendToService(Constant.VOLUME, "0.5", "");
                                    break;
                                case Constant.DECREASE_VOLUME:
                                    sendToService(Constant.VOLUME, "0.3", "");
                                    break;
                                case Constant.INCREASE_LIGHT:
                                    break;
                                case Constant.DECREASE_LIGHT:
                                    break;
                                default:
                            }
                        } else {
                            //唤醒失败
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else if ("wp.exit".equals(name)) {
                    //唤醒已停止
                }
            }
        };
        mEventManager.registerListener(mEventListener);
    }

    /**
     * 获取小节列表
     */
    private void getSectionList() {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                Connection connection = MainActivity.getConnection();
                Statement statement = connection.createStatement();
                String resource = "select * from  sectionresource where CID="
                        + mCourse.getCourseId() +
                        " order by SectionSort,VideoINSectionSort";
                ResultSet resultSet = statement.executeQuery(resource);
                while (resultSet.next()) {
                    Section section = new Section();
                    String sectionId = resultSet.getString(1);
                    section.setSectionId(sectionId);
                    section.setSectionName(resultSet.getString(3));
                    section.setSectionUrl(resultSet.getString(4));
                    section.setSectionDescribe(resultSet.getString(5));
                    section.setSectionDuration(resultSet.getInt(7));
                    section.setResourceDuration(resultSet.getInt(13));
                    section.setResourceUrl(resultSet.getString(14));
                    section.setResourceType(resultSet.getInt(18));
                    mResourceList.add(section);
                    //用于适配器列表
                    if (mSectionList.size() == 0) {
                        mSectionList.add(section);
                        mLastSectionId = sectionId;
                    } else {
                        if (!sectionId.equals(mLastSectionId)) {
                            mSectionList.add(section);
                            mLastSectionId = sectionId;
                        }
                    }
                }
                emitter.onNext(1);
                emitter.onComplete();
                resultSet.close();
                statement.close();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Object>() {
                    @Override
                    protected void onSuccess(Object o) {
                        mSectionAdapter.setDataList(mSectionList);
                        //初始化播放第一节播放视频

                        click(0);

                    }

                    @Override
                    protected void onFailure(int code, String message) {

                    }
                });
    }

    /**
     * 点击小节列表
     *
     * @param position
     */
    @Override
    public void click(int position) {
        mCurrentPosition = position;
        String sectionId = mSectionList.get(position).getSectionId();
        mSectionId = sectionId;
        sendToService(Constant.BEGIN, String.valueOf(mCourse.getCourseId()), mSectionId);

        if (mResourceType == 1) {
            skPlay.setProgress(0);
            mCurrentMills = 0;
            close();
        } else if (mResourceType == 2) {
            mMediaPlayer.stop();
            mMediaPlayer.setTime(0);
            skPlay.setProgress(0);
        }

        for (int i = 0; i < mResourceList.size(); i++) {
            if (sectionId.equals(mResourceList.get(i).getSectionId())) {
                mLocation = i;
                break;
            }
        }
        setResource(mLocation);
        updateBackground();
    }

    /**
     * 发送指令给服务器
     */
    private void sendToService(String type, String v1, String v2) {
        ApiManager.getInstance().requestService
                .sendCommand(type, v1, v2)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new BaseObserver<ResponseResult>() {
                    @Override
                    protected void onSuccess(ResponseResult responseResult) {
                    }

                    @Override
                    protected void onFailure(int code, String message) {

                    }
                });
    }

    /**
     * 播放资源
     */
    public void setResource(int location) {
        Section section = mResourceList.get(location);
        //播放的不同小节
        if (!mSectionId.equals(section.getSectionId())) {
            mSectionId = section.getSectionId();
            sendToService(Constant.BEGIN, String.valueOf(mCourse.getCourseId()), mSectionId);
            for (int i = 0; i < mSectionList.size(); i++) {
                if (mSectionId.equals(mSectionList.get(i).getSectionId())) {
                    mCurrentPosition = i;
                }
            }
            updateBackground();
        }
        tvSectionTitle.setText(section.getSectionName());
        tvSectionSummary.setText(section.getSectionDescribe());
        mResourceDuration = section.getResourceDuration();
        mResourceType = section.getResourceType();
        if (mResourceType == 1) {
            //播放图片
            ivPhotoPlayer.setVisibility(View.VISIBLE);
            isPhotoPlaying = true;
            skPlay.setMax(mResourceDuration);
            tvTotalTime.setText("/" + TimeFormatUtils.formatSeconds(mResourceDuration));
            GlideApp.with(CoursePlayActivity.this)
                    .load(Constant.LABEL + MyApplication.getInstance().getHost()
                            + Constant.RESOURCE_PORT + section.getResourceUrl())
                    .into(ivPhotoPlayer);
            updateProgress();
        } else if (mResourceType == 2) {
            //播放视频
            ivPhotoPlayer.setVisibility(View.INVISIBLE);
            Media media = new Media(mLibVLC,
                    Uri.parse(Constant.LABEL + MyApplication.getInstance().getHost()
                            + Constant.RESOURCE_PORT + section.getResourceUrl()));
            mMediaPlayer.setMedia(media);
            mMediaPlayer.play();
        }
        ibPlay.setImageResource(R.drawable.pause);
    }

    /**
     * 更新当前播放的小节样式
     */
    private void updateBackground() {
        tvSectionCount.setText((mCurrentPosition + 1) + "/" + mSectionList.size());
//        if (isFistInit) {
//            View currentView = mLinearManager.findViewByPosition(mCurrentPosition);
//            if (currentView != null) {
//                RecyclerView.ViewHolder holder = rlvSection.getChildViewHolder(currentView);
//                ConstraintLayout clSection = holder.itemView.findViewById(R.id.cl_section);
//                clSection.setBackgroundResource(R.drawable.bg_light_rectangle);
//                mLastPosition = mCurrentPosition;
//                isFistInit = false;
//            }
//        } else {
//            if (mLastPosition != mCurrentPosition) {
//                View currentView = mLinearManager.getChildAt(mCurrentPosition);
//                if (currentView != null) {
//                    ConstraintLayout clSection = currentView.findViewById(R.id.cl_section);
//                    clSection.setBackgroundResource(R.drawable.bg_light_rectangle);
//                }
//                View lastView = mLinearManager.getChildAt(mLastPosition);
//                if (lastView != null) {
//                    ConstraintLayout clSection = lastView.findViewById(R.id.cl_section);
//                    clSection.setBackgroundResource(android.R.color.transparent);
//                }
//                mLastPosition=mCurrentPosition;
//            }
//        }
    }

    /**
     * 图片播放时，更新进度条
     */
    public void updateProgress() {
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        if (!isPhotoPlaying) {
                            return;
                        }
                        if (mCurrentMills < mResourceDuration) {
                            mCurrentMills = mCurrentMills + 1000;
                            skPlay.setProgress(mCurrentMills);
                            String s = TimeFormatUtils.formatSeconds(mCurrentMills);
                            tvCurrentTime.setText(s);
                        } else {
                            //播放结束,继续播放下一节
                            onComplete();
                            mCurrentMills = 0;
                            isPhotoPlaying = false;
                            ibPlay.setImageResource(R.drawable.play);
                            if (mLocation < mResourceList.size() - 1) {
                                mLocation++;
                                setResource(mLocation);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        close();
                    }

                    @Override
                    public void onComplete() {
                        close();
                    }
                });
    }


    @Override
    public void onNewLayout(IVLCVout vlcVout, int width, int height, int visibleWidth, int visibleHeight, int sarNum, int sarDen) {
        skPlay.setMax(mResourceDuration);
        tvTotalTime.setText("/" + TimeFormatUtils.formatSeconds(mResourceDuration));
    }

    @Override
    public void onSurfacesCreated(IVLCVout vlcVout) {

    }

    @Override
    public void onSurfacesDestroyed(IVLCVout vlcVout) {

    }

    /**
     * 播放过程中的监听
     *
     * @param event
     */
    @Override
    public void onEvent(MediaPlayer.Event event) {
        long timeChanged = event.getTimeChanged();
        if (timeChanged == 0 || mResourceDuration == 0) {
            return;
        }
        Log.d("CoursePlay","timeChanged:"+timeChanged);
        skPlay.setProgress((int) timeChanged);
        tvCurrentTime.setText(TimeFormatUtils.formatSeconds(timeChanged));
        if (timeChanged > mResourceDuration) {
            //播放结束,继续播放下一个资源
            mMediaPlayer.stop();
            mMediaPlayer.setTime(0);
            ibPlay.setImageResource(R.drawable.play);
            if (mLocation < mResourceList.size() - 1) {
                mLocation++;
                setResource(mLocation);
            }
        }
    }

    /**
     * seekBar改变时
     *
     * @param seekBar
     * @param progress
     * @param b
     */
    @Override
    public void onProgressChanged(SeekBar seekBar, final int progress, boolean b) {
        if (seekBar.getId() == R.id.sk_voice) {
            //调用接口，传递数值
        } else {
            //调用接口，传递数值
//            Log.e("com.jimind.sportdemo", CommonUtils.setDoubleTwo(progress / 255));
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

    /**
     * 用于隐藏音量和亮度控制条
     *
     * @param view
     * @param motionEvent
     * @return
     */
    @Override
    public boolean onTouch(View view, final MotionEvent motionEvent) {
        //抬起手势，5s后消失
        if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
            if (view.getId() == R.id.sk_voice) {
                skVoice.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        sendToService(Constant.VOLUME, CommonUtils.setDoubleTwo(skVoice.getProgress() / (float) mMaxVolume), "");
                        skVoice.setVisibility(View.INVISIBLE);
                    }
                }, 2000);
            } else if (view.getId() == R.id.sk_light) {
                skLight.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        skLight.setVisibility(View.INVISIBLE);
                    }
                }, 2000);
            }
        }
        return false;
    }


    @OnClick({R.id.bt_stop, R.id.bt_record, R.id.bt_control,
            R.id.ib_play, R.id.ib_light, R.id.ib_voice})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_record:
                //语音授权
                initPermission();
                break;
            case R.id.bt_control:
                //屏幕控制
                break;
            case R.id.ib_play:
                //控制按钮
                controlPlay();
                break;
            case R.id.ib_light:
                //亮度调节
                skLight.setVisibility(View.VISIBLE);
                break;
            case R.id.ib_voice:
                //音量调节
                skVoice.setVisibility(View.VISIBLE);
                break;
            case R.id.bt_stop:
                //终止
                close();
                sendToService(Constant.STOP_COURSE, String.valueOf(mCourse.getCourseId()), "");
                Intent intent = new Intent(this, SummaryActivity.class);
                intent.putExtra(Constant.COURSE, mCourse);
                intent.putExtra(Constant.TOTAL_NUMBER, mTotalNumber);
                startActivity(intent);
                finish();
                break;
            default:
        }
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private void initPermission() {
        List<String> noPermissionList = new ArrayList<>();
        String[] permissions = {Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        for (String permission : permissions) {
            //没有权限
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                noPermissionList.add(permission);
            }
        }
        String tmpList[] = new String[noPermissionList.size()];
        if (!noPermissionList.isEmpty()) {
            ActivityCompat.requestPermissions(this, noPermissionList.toArray(tmpList), 123);
        } else {
            //已经全部授权
            start();
        }
    }

    /**
     * 动态授权回调
     *
     * @param requestCode  请求码
     * @param permissions  授权权限
     * @param grantResults 授权结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 123) {
            if (grantResults.length > 0) {
                for (int grantResult : grantResults) {
                    if (grantResult != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                }
                //权限全部同意
                start();
            }
        }
    }

    /**
     * 开始启动语音唤醒服务
     */
    private void start() {
        Toast.makeText(CoursePlayActivity.this, "您已开启语音服务！", Toast.LENGTH_SHORT).show();
        mEventManager.send(SpeechConstant.WAKEUP_START, mJson, null, 0, 0);
    }

    /**
     * 释放资源
     */
    public void release() {
        mEventManager.send(SpeechConstant.WAKEUP_STOP, null, null, 0, 0);
        mEventManager.unregisterListener(mEventListener);
        mEventManager = null;
    }

    /**
     * 控制播放
     */
    public void controlPlay() {
        if (mResourceType == 1) {
            if (isPhotoPlaying) {
                //播放中-->暂停
                sendToService(Constant.SUSPEND, "", "");
                isPhotoPlaying = false;
                ibPlay.setImageResource(R.drawable.play);
            } else {
                //暂停-->播放
                sendToService(Constant.CONTINUE, "", "");
                isPhotoPlaying = true;
                ibPlay.setImageResource(R.drawable.pause);
            }
        } else if (mResourceType == 2) {
            if (mMediaPlayer.isPlaying()) {
                //播放中-->暂停
                sendToService(Constant.SUSPEND, "", "");
                mMediaPlayer.pause();
                ibPlay.setImageResource(R.drawable.play);
            } else {
                //暂停-->播放
                sendToService(Constant.CONTINUE, "", "");
                mMediaPlayer.play();
                ibPlay.setImageResource(R.drawable.pause);
            }
        }
    }

    /**
     * 防止泄露
     */
    private void close() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //停止播放
        mMediaPlayer.stop();
        //取消屏幕常亮
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        release();
        //释放资源
        if (mMediaPlayer != null) {
            mMediaPlayer.getVLCVout().detachViews();
            mMediaPlayer.release();
            mMediaPlayer = null;
            mLibVLC.release();
            mLibVLC = null;
        }
    }
}
