package com.cooleshow.student.ui.mine;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.cooleshow.base.bean.EquipmentTestingBean;
import com.cooleshow.base.recorder.AudioRecorder;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.FileUtils;
import com.cooleshow.base.utils.NetworkUtil;
import com.cooleshow.base.widgets.DialogUtil;
import com.cooleshow.student.R;
import com.cooleshow.student.adapter.TestingListAdapter;
import com.cooleshow.student.contract.EquipmentTestContract;
import com.cooleshow.student.databinding.ActivityEquipmentTestBinding;
import com.cooleshow.student.presenter.mine.EquipmentTestPresenter;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/6/1 16:21
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.MineCenter.MINE_EQUIPMENT_TEST)
public class EquipmentTestActivity extends BaseMVPActivity<ActivityEquipmentTestBinding, EquipmentTestPresenter> implements EquipmentTestContract.EquipmentTestView, View.OnClickListener {

    private ImageView ivIcon;
    private TextView tvTitle;
    private TextView tvHint;
    private RecyclerView recyclerView;
    private Button btnCancel;
    private Button btnConfirm;
    private Button btnNext;
    private List<EquipmentTestingBean> list = new LinkedList<>();
    ;
    private int cont = 1;
    private AudioRecorder mAudioRecorder;
    private Timer timer;
    private boolean isRecording = false;
    private int recorderSecondsElapsed;
    private int playerSecondsElapsed;
    private String mFileName = null;
    private String mFilePath = null;
    private File mAudioFile;
    private boolean isPlaying = false;
    private Handler mHandler = new Handler();

    private MediaPlayer mMediaPlayer = null;
    private String fileLength;
    TestingListAdapter adapter;

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "设备检测");
        ivIcon = viewBinding.imageView;
        tvTitle = viewBinding.tvTitle;
        tvHint = viewBinding.tvHint;
        btnCancel = viewBinding.btnCancel;
        btnConfirm = viewBinding.btnConfirm;
        btnNext = viewBinding.btnNext;
        recyclerView = viewBinding.recyclerView;
        btnNext.setOnClickListener(this);

    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
    }
    @Override
    public void initData() {
        super.initData();
        list.clear();
        for (int i = 0; i < 6; i++) {
            EquipmentTestingBean bean = new EquipmentTestingBean();
            if (0 == i) {
                bean.setName("设备检测");
                bean.setContent("为确保您能正常上课，现在进行声音测试");
                bean.setIcon(R.drawable.icon_testing_phone);
                bean.setState(3);
            }
            if (1 == i) {
                bean.setName("手机话筒检测");
                bean.setContent("请按录音并念出下方文字\n“我正在测试话筒与扬声器”");
                bean.setIcon(R.drawable.icon_testing_recorder);
                bean.setState(4);
            }
            if (2 == i) {
                bean.setName("扬声器检测");
                bean.setContent("录音内容播放中请听是否有声音");
                bean.setIcon(R.drawable.icon_testing_play);
                bean.setState(4);
            }
            if (3 == i) {
                bean.setName("设备检测成功");
                bean.setContent("恭喜您！话筒与扬声器测试已通过");
                bean.setIcon(R.drawable.icon_recorder_success);
                bean.setState(4);
            }
            if (4 == i) {
                bean.setName("网络检测成功");
                bean.setContent("您当前的网络状态良好");
                bean.setIcon(R.drawable.icon_testing_network);
                bean.setState(4);
            }
            if (5 == i) {
                bean.setName("通知权限");
                bean.setContent("通知权限未开启，可能错过上课提醒哦！快去开启通知权限吧~");
                bean.setIcon(R.drawable.icon_testing_notice);
                bean.setState(4);
            }
            list.add(bean);
        }

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 6);
        recyclerView.setLayoutManager(gridLayoutManager);
        adapter = new TestingListAdapter(this, list);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_next:
                list.get(0).setState(1);
                switch (cont) {
                    case 1:
                        cont = 2;
                        tvTitle.setText(list.get(1).getName());
                        SpannableString spannableString = new SpannableString(list.get(1).getContent());
                        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(com.cooleshow.base.R.color.color_f97215)), 12, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        tvHint.setText(spannableString);
                        list.get(1).setState(3);
                        btnNext.setText("开始录音");
                        ivIcon.setImageResource(list.get(1).getIcon());
                        break;
                    case 2:
                    case 3:
                        if (!isRecording) {
                            cont = 3;
                            startRecorder();
                            btnNext.setText("停止录音");
                        } else {
                            cont = 4;
                            stopRecorder();
                            startPlaying();
                            btnNext.setText("下一步");
                            btnConfirm.setVisibility(View.VISIBLE);
                            btnCancel.setVisibility(View.VISIBLE);
                            btnNext.setVisibility(View.GONE);
                            tvTitle.setText(list.get(2).getName());
                            tvHint.setText(list.get(2).getContent());
                            ivIcon.setImageResource(list.get(2).getIcon());
                            list.get(1).setState(1);
                            list.get(2).setState(3);
                            btnCancel.setOnClickListener(view1 -> {
                                stopPlaying();
                                list.get(1).setState(2);
                                list.get(2).setState(2);
                                list.get(3).setState(2);
                                list.get(4).setState(3);
                                tvTitle.setText("设备检测失败");
                                tvHint.setText("话筒或者扬声器故障,请检查设备是否处于静音或者音量过低");
                                btnNext.setVisibility(View.VISIBLE);
                                btnConfirm.setVisibility(View.GONE);
                                btnCancel.setVisibility(View.GONE);
                                adapter.setData(list, cont);

                            });
                            btnConfirm.setOnClickListener(view1 -> {
                                stopPlaying();
                                list.get(2).setState(1);
                                list.get(3).setState(1);
                                list.get(4).setState(3);
                                tvTitle.setText(list.get(3).getName());
                                tvHint.setText(list.get(3).getContent());
                                ivIcon.setImageResource(list.get(3).getIcon());
                                btnNext.setVisibility(View.VISIBLE);
                                btnConfirm.setVisibility(View.GONE);
                                btnCancel.setVisibility(View.GONE);
                                adapter.setData(list, cont);

                            });
                        }
                        break;
                    case 4:
                        cont = 5;
                        btnNext.setText("下一步");
                        ivIcon.setImageResource(list.get(4).getIcon());
                        list.get(5).setState(3);
                        if (NetworkUtil.isNetworkAvailable(this)) {
                            if (NetworkUtil.getNetWorkType(this) == NetworkUtil.NETWORKTYPE_3G || NetworkUtil.getNetWorkType(this) == NetworkUtil.NETWORKTYPE_WIFI) {
                                list.get(4).setState(1);
                                tvTitle.setText(list.get(4).getName());
                                tvHint.setText(list.get(4).getContent());
                            } else {
                                list.get(4).setState(2);
                                tvTitle.setText("网络检测失败");
                                tvHint.setText("当前网络不畅，请检查网络状态");
                            }

                        } else {
                            list.get(4).setState(2);
                            tvTitle.setText("网络检测失败");
                            tvHint.setText("当前无网络连接，请检查网络状态");
                        }
                        break;
                    case 5:
                        cont = 6;
                        tvTitle.setText(list.get(5).getName());

                        ivIcon.setImageResource(list.get(5).getIcon());
                        btnNext.setText("完成检测");
                        if (isNotificationEnabled(this)) {
                            list.get(5).setState(1);
                            tvHint.setText("通知权限已开启，再也不会错过上课提醒了");
                        } else {
                            list.get(5).setState(2);
                            tvHint.setText(list.get(5).getContent());
                            DialogUtil.showInCenter(getSupportFragmentManager(), com.cooleshow.base.R.layout.common_popu, (holder, dialog1) -> {
                                TextView tvTitle = holder.getView(R.id.tv_title);
                                TextView tvContent = holder.getView(R.id.tv_content);
                                TextView btncancel = holder.getView(R.id.btn_cancel);
                                TextView btnCommit = holder.getView(R.id.btn_commit);
                                tvTitle.setText("是开启通知权限？");
                                tvContent.setText("");
                                btncancel.setOnClickListener(view1 -> {
                                    dialog1.dismiss();
                                });
                                btnCommit.setOnClickListener(view1 -> {
                                    finish();
                                    dialog1.dismiss();
                                    gotoSet();
                                });
                            });

                        }
                        break;
                    case 6:
                        finish();
                        break;
                }
                adapter.setData(list, cont);
        }
    }

    @Override
    protected ActivityEquipmentTestBinding getLayoutView() {
        return ActivityEquipmentTestBinding.inflate(getLayoutInflater());
    }

    @Override
    protected EquipmentTestPresenter createPresenter() {
        return new EquipmentTestPresenter();
    }


    private void startRecorder() {

        isRecording = true;
        stopPlaying();
        mFileName = "/麦克风测试.aac";
        mFilePath = FileUtils.getCacheDir(this);

        //        File fileDirectory = new File(mFilePath);
        //        if (!fileDirectory.exists()) {
        //            fileDirectory.mkdirs();
        //        }

        File mAudioFile = new File(mFilePath + mFileName);
        mAudioRecorder = AudioRecorder.getInstance();
        mAudioRecorder.prepareRecord(MediaRecorder.AudioSource.MIC,
                MediaRecorder.OutputFormat.AAC_ADTS, MediaRecorder.AudioEncoder.AAC,
                mAudioFile);
        mAudioRecorder.startRecord();
    }

    private void stopRecorder() {
        isRecording = false;
        if (null != mAudioRecorder) {
            mAudioRecorder.stopRecord();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopRecorder();
        stopPlaying();
        if (null != mAudioFile) {
            FileUtils.deleteFile1(mAudioFile);

        }
    }

    private void startPlaying() {
        mMediaPlayer = new MediaPlayer();

        try {
            mMediaPlayer.setDataSource(mFilePath + mFileName);
            mMediaPlayer.prepare();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMediaPlayer.start();
                }
            });
        } catch (IOException e) {
        }

        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopPlaying();
            }
        });
    }


    private void pausePlaying() {
        mMediaPlayer.pause();
    }

    private void resumePlaying() {
        mMediaPlayer.start();
    }

    private void stopPlaying() {
        if (mMediaPlayer == null || mHandler == null) {
            return;
        }
        mMediaPlayer.stop();
        mMediaPlayer.reset();
        mMediaPlayer.release();
        mMediaPlayer = null;

        isPlaying = !isPlaying;
        //allow the screen to turn off again once audio is finished playing
    }

    private boolean isNotificationEnabled(Context context) {
        boolean isOpened = false;
        try {
            isOpened = NotificationManagerCompat.from(context).areNotificationsEnabled();
        } catch (Exception e) {
            e.printStackTrace();
            isOpened = false;
        }
        return isOpened;

    }

    private void gotoSet() {

        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", getPackageName());
            intent.putExtra("app_uid", getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

    }

}
