package com.example.mediademo;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.itgsa.opensdk.common.OnConnectionSucceedListener;
import com.itgsa.opensdk.media.MediaClient;
import com.itgsa.opensdk.media.extensions.KtvSupportInfo;
import com.itgsa.opensdk.media.extensions.MediaClientUtil;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MEDIA_DEMO";

    private static final boolean ONLY_TEST_API = false;

    private MediaClient mMediaClient;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ONLY_TEST_API) {
            onlyTestAPIForKTV();
            return;
        }

        // Test KTV features using demo
        gotoTestKTV();
    }

    private void gotoTestKTV() {
        startActivity(new Intent(this, KTVActivity.class));
    }

//    private boolean isVivoOs() {
//        return "vivo".equals(android.os.Build.MANUFACTURER);
//    }

    // Generally redundant, meaningless APIs
    @Deprecated
    private boolean isKtvNewApiSupported_MeaninglessAPICalls() {
        // OVM联盟sdk版本号
        int version = mMediaClient.getVersion();
        Log.d(TAG, "version is: " + version);
        //不支持的版本，三方可选择自行适配（部分接口如果后续进行了拓展需要）
        if (version < 10000) {
            //其他替代方案或界面提示
            Log.d(TAG, "version is not supported");
            return false;
        } else {
            Log.d(TAG, "version is supported");
        }

        // 判断当前机器设备能否支持KTV
        boolean isSupportedForDevice = mMediaClient.isDeviceSupportKaraoke();
        if (isSupportedForDevice) {
            Log.d(TAG, "KTV is supported for current device");
        } else {
            Log.d(TAG, "KTV is not supported for current device");
            return false;
        }

        // 判断KTV是否支持当前APP
        boolean isSupportedForApp = mMediaClient.isAppSupportKaraoke(getApplicationContext().getPackageName());
        if (isSupportedForApp) {
            Log.d(TAG, "KTV is supported for current APP");
        } else {
            Log.d(TAG, "KTV is not supported for current device");
            return false;
        }
        return true;
    }

//    private boolean isKtvNewApiSupported() {
//        return MediaClientUtil.isKtvNewApiSupported(mMediaClient);
//    }

    private void onlyTestAPIForKTV() {

        mMediaClient = MediaClient.initialize(getApplicationContext());

        // Generally redundant, meaningless APIs
//        if (isKtvNewApiSupported_MeaninglessAPICalls()) {  // TODO NOTE: We'd better NOT use this judgment
//        }


        // Whether the ability of KTV new API compatibility supports
        // Indicates app is on the new architecture of KTV API
        // True if the new API of KTV is supported, running on this device by using new API
        // TODO NOTE: Recommend this judgement
        if (mMediaClient.isSupported()) {
            // or use this, same result
//        if (MediaClientUtil.isKtvNewApiSupported(mMediaClient)) {
            Log.d(TAG, "KTV is supported for the new architecture of KTV APIs, you can use them");
            if (MediaClientUtil.isOsOppo()) {
                mMediaClient.addOnConnectionSucceedListener(new OnConnectionSucceedListener() {
                    @Override
                    public void onConnectionSucceed() {
                        Log.i(TAG, "connectionSucceed");
                        onKtvNewApiSupported();
                    }
                });
            } else {
                onKtvNewApiSupported();
            }
        } else {
            Log.d(TAG, "KTV is not supported for the new architecture of KTV APIs, " +
                    "you CAN NOT use them");
            // do something
            //不支持的版本，三方可选择自行适配（部分接口如果后续进行了拓展需要）
            //其他替代方案或界面提示
            Log.d(TAG, "new APIs of KTV is not supported for your APP!");

            // NOTE: 可以不用下面这个判断逻辑了，因为本来就不支持

//            // OVM联盟sdk版本号
//            int version = mMediaClient.getVersion();
//            Log.d(TAG, "version is: " + version);
//            //不支持的版本，三方可选择自行适配（部分接口如果后续进行了拓展需要）
//            if (version < 10000) {
//                //其他替代方案或界面提示
//                Log.d(TAG, "version is not supported");
//            } else {
//                Log.d(TAG, "API version is supported, but KTV is not supported for your APP!");
//            }
        }
    }

    private void onKtvNewApiSupported() {
        // 应用获取当前机器支持KTV的参数信息，比如应用设置何种参数（AudioTrack的采样率、flag等，AudioRecord的source等），可以正常使用KTV功能
        //
        // 若支持任意参数, value置为"default";
        // 没有返回的key, value为默认值"default";
        // 所有value给十进制数值的字符串形式, 例如AUDIO_SOURCE_MIC需要返回"1", AUDIO_OUTPUT_FLAG_DEEP_BUFFER需要返回"8"
        //
        // FOR VIVO examples:
        // {
        //    "audioTrackParam": [
        //        {
        //            "streamType": "3",
        //            "sampleRate": "48000",
        //            "format": "default",
        //            "flag": "8"
        //        },
        //        {
        //            "streamType": "3",
        //            "sampleRate": "44100",
        //            "format": "default",
        //            "flag": "8"
        //        }
        //    ],
        //    "audioRecordParam": [
        //        {
        //            "streamType": "default",
        //            "sampleRate": "48000",
        //            "format": "default",
        //            "flag": "default",
        //            "source": "0"
        //        },
        //        {
        //            "streamType": "default",
        //            "sampleRate": "48000",
        //            "format": "default",
        //            "flag": "default",
        //            "source": "1"
        //        }
        //    ],
        //    "isSupportToneMode": false
        //}
        String ktvSupportInfoJson = mMediaClient.getKaraokeSupportParameters();
        Log.d(TAG, "KTV ktvSupportInfoJson: " + ktvSupportInfoJson);

        KtvSupportInfo supportInfo = new Gson().fromJson(ktvSupportInfoJson, KtvSupportInfo.class);
        Log.d(TAG, "KTV isSupportListenRecordSame: " + supportInfo.isSupportListenRecordSame);
        Log.d(TAG, "KTV isSupportExtSpeakerParam: " + supportInfo.isSupportExtSpeakerParam);
        Log.d(TAG, "KTV isSupportToneMode: " + supportInfo.isSupportToneMode);

        KtvSupportInfo.TrackSupportInfo targetTrackInfo =
                new KtvSupportInfo.TrackSupportInfo("3", "48000", "2", "8");
        Log.d(TAG, "KTV targetTrackInfo: " + targetTrackInfo.toString());

        if (!MediaClientUtil.isTargetAudioSupported(supportInfo, targetTrackInfo)) {
            return;
        }
        // track equals

        KtvSupportInfo.RecordSupportInfo targetRecordInfo =
                new KtvSupportInfo.RecordSupportInfo("default", "48000", "2", "8", "0");
        Log.d(TAG, "KTV targetRecordInfo: " + targetRecordInfo.toString());

        if (!MediaClientUtil.isTargetAudioSupported(supportInfo, targetRecordInfo)) {
            return;
        }
        // record equals

        Log.d(TAG, "test KTV openKTVDevice");
        mMediaClient.openKTVDevice();

        // 听录一致，选择录音输出数据，建议接口调用动作应发生在openKTVDevice后与录音前
        // 0：录音输出为原始录音数据；1：录音输出为录音+应用playback数据，就是耳返数据（直播场景用）；
        mMediaClient.setListenRecordSame(1);
        int recordSrcMode = mMediaClient.getListenRecordSame();
        Log.d(TAG, "KTV ListenRecordSame mode: " + recordSrcMode);

        // TODO NOTE: Must use the field supported to check API!!!
        if (supportInfo.isSupportExtSpeakerParam) {
            if (MediaClientUtil.isOsVivo()) {
                testVivoKTV();
            }
        } else if (supportInfo.isSupportToneMode) {
            Log.d(TAG, "setToneMode from SDK!");
            mMediaClient.setToneMode(5);
        }

        // 设置人声音量大小，0~15 （OPPO是0-12，请OPPO确认）
        mMediaClient.setMicVolParam(8);
        // 获取当前yamaha人声音量值
        // value ：0~15
        int micVolume = mMediaClient.getMicVolParam();
        Log.d(TAG, "KTV micVolume: " + micVolume);

        // 设置混响效果的音效种类，以及获取额外音效种类
        // 类型( 0:无、1:KTV、2:剧场、3:音乐厅、4:录音棚 )
        mMediaClient.setMixerSoundType(1);
        // For VIVO extensions as bellow:
        // 10: 温暖, 11: 空灵, 12: 3D迷幻, 13: 老唱片
        int[] extSoundTypes = mMediaClient.getExtMixerSoundType();
        if (extSoundTypes != null) {
            int testOne = 0;
            for (int extSoundType : extSoundTypes) {
                Log.d(TAG, "KTV extSoundTypes: " + extSoundType);

                // just test one
                if (testOne == 0) {
                    testOne = 1;
                    // You can use it
                    mMediaClient.setMixerSoundType(extSoundType);
                }
            }
        }

        // 设置均衡器EQ效果的音效种类，以及获取额外音效种类
        // 类型( 0:无、1:标准、2:浑厚、3:清脆、4:明亮 )
        mMediaClient.setEqualizerType(1);
        // For VIVO extensions as bellow:
        // 10: 温暖, 11: 空灵, 12: 3D迷幻, 13: KTV
        int[] extEqTypes = mMediaClient.getExtEqualizerType();
        if (extEqTypes != null) {
            int testOne = 0;
            for (int extEqType : extEqTypes) {
                Log.d(TAG, "KTV extEqTypes: " + extEqType);

                // just test one
                if (testOne == 0) {
                    testOne = 1;
                    // You can use it
                    mMediaClient.setEqualizerType(extEqType);
                }
            }
        }

        // 控制耳返开启/关闭接口，系统默认打开，建议无论怎么app调用都打开调用一次，排除其他app不正确调用的干扰。
        // 0 关闭：1 开启
        mMediaClient.setPlayFeedbackParam(1);
        // 获取当前耳返开关状态
        // 0：开关未打开  1：开关已打开
        int feedbackPlayState = mMediaClient.getPlayFeedbackParam();
        Log.d(TAG, "KTV feedbackPlayState: " + feedbackPlayState);

        Log.d(TAG, "test KTV closeKTVDevice");
        mMediaClient.closeKTVDevice();

        Log.d(TAG, "test KTV END");
    }

    private void testVivoKTV() {
        Log.d(TAG, "testVivo KTV START");

        // 控制外接音响设备开关，这个接口的开出是为了当用户使用大音响或者大功放设备K歌，此情景下啸叫厉害，故开了此接口。
        // 注意：该接口在三个手机平台中都调用了也没有关系，只是在不支持的手机中不会有该功能，因此只有vivo手机中调用才起作用
        // 0：关  1：开
        mMediaClient.setExtSpeakerParam(1);
        // 获取当前外接音响设备开关状态。
        // 0：开关未打开  1：开关已打开
        int extSpkState = mMediaClient.getExtSpeakerParam();
        Log.d(TAG, "KTV extSpkState: " + extSpkState);

        Log.d(TAG, "testVivo KTV END");
    }

//    public Gson createGson() {
//        GsonBuilder builder = new GsonBuilder();
//        builder.registerTypeAdapter(Integer.class, new IntegerDefaultAdapter());
//        builder.registerTypeAdapter(String.class, new StringDefaultAdapter());
//        return builder.create();
//    }
//
//    public class IntegerDefaultAdapter extends TypeAdapter<Integer> {
//
//        @Override
//        public void write(JsonWriter jsonWriter, Integer integer) throws IOException {
//            jsonWriter.value(String.valueOf(integer));
//        }
//
//        @Override
//        public Integer read(JsonReader jsonReader) throws IOException {
//            try {
//                return Integer.valueOf(jsonReader.nextString());
//            } catch (NumberFormatException e) {
//                e.printStackTrace();
//                return -1;
//            }
//        }
//    }
//
//    public class StringDefaultAdapter extends TypeAdapter<String> {
//
//        @Override
//        public void write(JsonWriter jsonWriter, String s) throws IOException {
//            jsonWriter.value(s);
//        }
//
//        @Override
//        public String read(JsonReader jsonReader) throws IOException {
//            if (jsonReader.peek() == JsonToken.NULL) {
//                jsonReader.nextNull();
//                return "";
//            } else {
//                return jsonReader.nextString();
//            }
//        }
//    }
//
//    public class StringNullAdapter extends TypeAdapter<String> {
//
//        @Override
//        public void write(JsonWriter writer, String value) throws IOException { // TODO Auto-generated method stub
//            if (value == null) {
//                writer.nullValue();
//                return;
//            }
//            writer.value(value);
//        }
//
//        @Override
//        public String read(JsonReader reader) throws IOException { // TODO Auto-generated method stub
//            if (reader.peek() == JsonToken.NULL) {
//                reader.nextNull();
//                return "";
//            }
//            return reader.nextString();
//        }
//    }

}
