package com.bgycc.smartcanteen.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.speech.tts.TextToSpeech;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;

import static com.bgycc.smartcanteen.utils.SmartCanteenUtils.TAG;

public class TTSHelper {
    private static boolean mSupportTTS = false;
    private static TextToSpeech mTTS = null;
    private static SoundPool mSoundPool;
    private static final HashMap<String, Integer> mSoundIdMap = new HashMap<>();

    public static void initialize(Context context) {
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                .setLegacyStreamType(AudioManager.STREAM_SYSTEM)
                .build();
        mSoundPool = new SoundPool.Builder()
                .setAudioAttributes(audioAttributes)
                .build();
        mSoundPool.setOnLoadCompleteListener((soundPool, sampleId, status) -> {
            if (status == 0) {
                soundPool.play(sampleId, 1f, 1f, 100, 0, 1f);
            }
        });
        mTTS = new TextToSpeech(context, status -> {
            if (status == TextToSpeech.SUCCESS) {
                int result = mTTS.setLanguage(Locale.CHINESE);
                mSupportTTS = result >= TextToSpeech.LANG_AVAILABLE;
            }
        });
        mSoundIdMap.clear();
    }

    public static void speak(String msg) {
        // 设备不支持tts时播放预定义音频
        if (mTTS == null || !mSupportTTS) {
            playSound(msg);
            return;
        }
        // beep默认播放音效,否则会变成人声朗读b-e-e-p
        if (msg.equals("beep")) {
            playSoundActual("beep.mp3");
            return;
        }
        mTTS.speak(msg, TextToSpeech.QUEUE_FLUSH, null, null);
    }

    public static void release() {
        mSoundIdMap.clear();
        if (mTTS != null) {
            mTTS.stop();
        }
        if (mSoundPool != null) {
            mSoundPool.release();
        }
    }

    private static void playSound(String msg) {
        String soundName;
        switch (msg) {
            case "beep":
                soundName = "beep.mp3";
                break;
            case "无效二维码":
                soundName = "qrcode-invalid.mp3";
                break;
            case "请勿重复扫码":
                soundName = "qrcode-repeat.mp3";
                break;
            case "支付成功":
                soundName = "pay-success.mp3";
                break;
            case "支付失败":
                soundName = "pay-fail.mp3";
                break;
            case "未获取到当前设备信息":
                soundName = "pay-device-not-found.mp3";
                break;
            case "设备已禁用":
                soundName = "pay-device-disable.mp3";
                break;
            case "未设置食堂参数":
                soundName = "pay-canteen-params-unset.mp3";
                break;
            case "当前不支持第三方支付":
                soundName = "pay-unsupported-other-platform.mp3";
                break;
            case "超过扣款限制":
                soundName = "pay-over-cost-limit.mp3";
                break;
            case "设备未绑定商品":
                soundName = "pay-unbind.mp3";
                break;
            case "扣款金额为0":
                soundName = "pay-price-zero.mp3";
                break;
            case "未获取到当前用户信息":
                soundName = "pay-no-user-info.mp3";
                break;
            case "已就餐,请勿重复支付":
                soundName = "pay-once.mp3";
                break;
            case "您的就餐权限已失效":
                soundName = "pay-invalid-permission.mp3";
                break;
            case "非本窗口营业时间":
                soundName = "pay-window-rest-time.mp3";
                break;
            case "非营业时间":
                soundName = "pay-canteen-rest-time.mp3";
                break;
            case "可用余额不足":
                soundName = "pay-balance-not-enough.mp3";
                break;
            case "第三方支付异常":
                soundName = "pay-other-platform-offline.mp3";
                break;
            case "支付成功(异常时间)":
                soundName = "pay-success-error-time.mp3";
                break;
            default:
                soundName = "pay-fail.mp3";
                break;
        }
        playSoundActual(soundName);
    }

    private static void playSoundActual(String name) {
        AssetManager assetManager = Utils.getApp().getAssets();
        Integer id = mSoundIdMap.get(name);
        if (id == null) {
            try {
                id = mSoundPool.load(assetManager.openFd(name), 1);
            } catch (IOException e) {
                LogUtils.e(TAG, "语音播放失败: " + name, e);
            }
            mSoundIdMap.put(name, id);
        } else {
            mSoundPool.play(id, 1f, 1f, 0, 0, 1f);
        }
    }
}