package com.tofly.ghrq_route.common.util.recorder;

import android.Manifest;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import androidx.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.manager.MediaManager;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.gaoyuan.weixinrecord.utils.PermissionHelper.PermissionListener;
import com.mgq.base.utils.toast.ToastUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Amu on 2017/4/13.
 */

public class AudioRecordHelper {

    private Context mContext;

    private PermissionHelper permissionHelper;

    private MyAudioRecordButton audioRecordButton;

    private List<AnimationDrawable> mAnimationDrawables = new ArrayList<>();

    private final String recordPermission = Manifest.permission.RECORD_AUDIO;
    private final String storagePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;

    public AudioRecordHelper(@NonNull Context context, @NonNull PermissionHelper helper,
                             @NonNull MyAudioRecordButton recordButton){
        mContext = context;
        permissionHelper = helper;
        audioRecordButton = recordButton;
    }

    public AudioRecordHelper(@NonNull Context context) {
        mContext = context;
    }

    public void initRecordButton(){
        boolean hasRecordPermission = checkRecordPermission();
        if (hasRecordPermission){
            audioRecordButton.setCanRecord(true);
        }else {
            audioRecordButton.setCanRecord(false);
            audioRecordButton.setText("点击获取录音权限");
            audioRecordButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    requestRecordPermission();
                }
            });
        }
    }

    public boolean checkRecordPermission(){
        return PermissionHelper.hasPermissions(mContext, recordPermission, storagePermission);
    }

    public void requestRecordPermission(){
        String hintStr = "音频录制请授予[录音]，[读写]权限，否则无法录音";
        permissionHelper.requestPermissions(hintStr,
                new PermissionListener() {
                    @Override
                    public void doAfterGrand(String... permission) {
                        String errStr = "已获取录音权限，请长按录音按钮进行录制";
                        ToastUtil.showToast(mContext, errStr);
                        audioRecordButton.setCanRecord(true);
                    }

                    @Override
                    public void doAfterDenied(String... permission) {
                        String errStr = "请授权,否则无法录音";
                        ToastUtil.showToast(mContext, errStr);
                        audioRecordButton.setCanRecord(true);
                    }
                }, recordPermission, storagePermission);
    }

    public View getRecordViewFromAudio(final Record record, final List<Record> records, final RecordClickListener listener){
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View rootView = inflater.inflate(R.layout.item_audio_record, null);
        rootView.setTag(record);

        TextView textTime = (TextView) rootView.findViewById(R.id.textview_audio_time);
        ImageView imageRead = (ImageView) rootView.findViewById(R.id.image_audio_read);

        //设置显示时长
        textTime.setText(record.getSecond() <= 0 ? 1 + "''" : record.getSecond() + "''");
        imageRead.setVisibility(!record.isPlayed() ? View.VISIBLE : View.GONE);
        rootView.setOnClickListener((View.OnClickListener) view -> {
            Record record1 = (Record) view.getTag();
            record1.setPlayed(true);
            ImageView imageRead1 = (ImageView) view.findViewById(R.id.image_audio_read);
            imageRead1.setVisibility(View.GONE);
            LinearLayout layoutSignal = (LinearLayout) view.findViewById(R.id.layout_audio_signal);
            final AnimationDrawable animationDrawable = (AnimationDrawable) layoutSignal.getBackground();
            //重置动画
            resetAnim(animationDrawable);
            //重置数据状态
            resetData(records);

            //处理点击正在播放的语音时，可以停止；再次点击时重新播放。
            if (record1.isPlaying()) {
                record1.setPlaying(false);
                MediaManager.release();//重置
            } else {
                record1.setPlaying(true);
                //获取语音信号栏，开始播放动画
                animationDrawable.start();
                //播放前重置。
                MediaManager.release();
                //开始实质播放
                MediaManager.playSound(record1.getPath(),
                        mp -> {
                            animationDrawable.selectDrawable(0);//显示动画第一帧
                            animationDrawable.stop();
                        });
            }
        });

        rootView.setOnLongClickListener(view -> {
            String title = "删除录音";
            String content = "是否删除录音?";
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(title);
            builder.setMessage(content);
            builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
                Record record1 = (Record) view.getTag();
                if (record1.isPlaying()) {
                    record1.setPlaying(false);
                    MediaManager.release();//重置
                }
                String file = record1.getPath();
                com.mgq.base.utils.file.FileUtil.deleteFile(file);
                if (listener != null)
                    listener.onRemoveRecord(view, record1);
            });
            builder.setNegativeButton(android.R.string.cancel, null);
            builder.show();
            return true;
        });

        return rootView;
    }

    private void resetData(List<Record> records) {
        if (records != null){
            for (Record record : records) {
                record.setPlaying(false);//保证在第二次点击该语音栏时当作没有“不是在播放状态”。
            }
        }
    }

    private void resetAnim(AnimationDrawable animationDrawable) {
        if (!mAnimationDrawables.contains(animationDrawable)) {
            mAnimationDrawables.add(animationDrawable);
        }
        for (AnimationDrawable ad : mAnimationDrawables) {
            ad.selectDrawable(0);
            ad.stop();
        }
    }

    public interface RecordClickListener{
        void onRemoveRecord(View view, Record record);
    }

    public static int getAudioLength(String filePath) {
        int duration = -1;
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            duration = mediaPlayer.getDuration();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return duration;
    }

}
