package com.ez.ertc.meeting;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.os.Environment;

import com.ez.basertc.RTCConstant;
import com.ez.baselib.utils.LogUtil;
import com.ez.basertc.RTCListener;
import com.ez.dclog.EZDcLogEventPresenter;
import com.ez.dclog.EZDcLogEventTypes;
import com.ez.dclog.params.event.ERTCEventToken;
import com.ez.ertc.meeting.constant.MtSets;
import com.ez.ertcengine.ERTCEngine;

import io.reactivex.Observable;

public class ErtcEzmHelper {
    public static ERTCEngine ertcEngine = null;
    private static ErtcEzmHelper instance;
    private static EzmLifecycleCallback ezmLifecycleCallback;
    private static Context mContext = null;
    private String ertcTestSecretDebug, ertcTestAppIdDebug, ertcTestAppKeyDebug;
    private RTCConstant.ErtcAudioCodeType ertcAudioCodeType;
    private String ertcToken;

    public static ErtcEzmHelper getInstance() {
        if (instance == null) {
            synchronized (ErtcEzmHelper.class) {
                if (instance == null) {
                    instance = new ErtcEzmHelper();
                }
            }
        }
        return instance;
    }

    protected static void onBackground(boolean background) {
        LogUtil.i("EZRTCImpl", "onBackground===" + background);
        if (ezmLifecycleCallback != null) {
            ezmLifecycleCallback.onBackground(background);
        }
    }

    public static void setEzmLifecycleCallback(EzmLifecycleCallback callback) {
        ezmLifecycleCallback = callback;
    }

    public static Context getContext() {
        return mContext;
    }

//    public void setErtcTestSecretDebug(String ertcTestSecretDebug) {
//        this.ertcTestSecretDebug = ertcTestSecretDebug;
//    }
//
//    public String getErtcTestSecretDebug() {
//        return ertcTestSecretDebug;
//    }

    public void setErtcTestAppIdDebug(String ertcTestAppIdDebug) {
        this.ertcTestAppIdDebug = ertcTestAppIdDebug;
    }

    public RTCConstant.ErtcAudioCodeType getErtcAudioCodeType() {
        return ertcAudioCodeType;
    }

    public void setErtcAudioCodeType(RTCConstant.ErtcAudioCodeType ertcAudioCodeType) {
        this.ertcAudioCodeType = ertcAudioCodeType;
    }

    public String getErtcTestAppIdDebug() {
        return ertcTestAppIdDebug;
    }
//
//    public void setErtcTestAppKeyDebug(String ertcTestAppKeyDebug) {
//        this.ertcTestAppKeyDebug = ertcTestAppKeyDebug;
//    }

    public String getErtcToken() {
        return ertcToken;
    }

    public void setErtcToken(String token) {
        ertcToken = token;
    }

    public void ertcInit(Application application) {
        mContext = application.getApplicationContext();
        application.registerActivityLifecycleCallbacks(new EzmLifecycleListener());
//        RestfulUtils.init(mContext);
    }

    @SuppressLint("NewApi")
    public Observable<ERTCEngine> ertcEnterInitDebug(final Context context) {
        if (ertcEngine != null) return Observable.just(ertcEngine);
        return Observable.create(emitter -> {
            long startTime = System.currentTimeMillis();
            try {
//                String accessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJFUlRDIiwiYXVkIjoiYzIzMTYzYmVkYWRhNDVkYWJlMzc1NDA5NTE1M2EwMzIiLCJ0cCI6ImF0IiwiZXhwIjoxNjk5MDYyNjc5LCJpYXQiOjE2OTgxOTg2Nzl9.iKEjkkpKEL49vpA-moSQnlNn8kSlbvbFvjjGlY86Dn0";
//                String accessToken = RtcAPI.Companion.getInstance().getAccessToken(ertcTestAppKeyDebug, ertcTestSecretDebug);
//                EZDcLogEventPresenter.getInstance().submitEvent(mContext, EZDcLogEventTypes.EVENT_EVENT_ACCESS_TOKEN, System.currentTimeMillis() - startTime, null,
//                        ERTCEventToken.getInstance()
//                                .setAppID(ertcTestAppIdDebug)
//                                .setToken(accessToken)
//                );
//
//                if(accessToken != null) {
                    RTCConstant.RTCEngineConfig config = new RTCConstant.RTCEngineConfig();
                    config.appId = ertcTestAppIdDebug;
    //                config.appKey = ertcTestAppKeyDebug;
    //                config.appSecret = ertcTestSecretDebug;
                    config.logLevel = LogUtil.ERTC_LOG_LEVEL_DEBUG;
                    config.audioCodeType = ertcAudioCodeType;
//                    config.accessToken = accessToken;
                    config.context = context.getApplicationContext();
                    config.logPath = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getPath();
                    ERTCEngine engine = ERTCEngine.init(config, new ERTCEngine.OnInitListener() {
                        @Override
                        public void onInitialization(ERTCEngine engine) {
                            ertcEngine = engine;
                            LogUtil.d("EZRTCImpl", "Init OK");
                            ertcEngine.setERTCDebugVideoLog(MtSets.isSaveAVData());
                            emitter.onNext(ertcEngine);
                        }

                        @Override
                        public void onError(int code) {
                            LogUtil.d("EZRTCImpl", "Init failed error:" + code);
                            emitter.onError(new Throwable(String.valueOf(code)));
                        }
                    });
//                } else {
//                    emitter.onError(new Throwable("get accessToken error"));
//                }
            } catch (Exception e) {
                e.printStackTrace();
                EZDcLogEventPresenter.getInstance().submitEvent(mContext.getApplicationContext(), EZDcLogEventTypes.EVENT_EVENT_ACCESS_TOKEN, System.currentTimeMillis() - startTime, String.valueOf(e.getMessage()), ERTCEventToken.getInstance().setAppID(ertcTestAppIdDebug).setErrorCode(String.valueOf(e.getMessage())));
            }
        });
    }

//    public Observable<String> getErtcToken(final String userId, final String roomId) {
//        return getErtcTokenDebug(userId, roomId);
//    }

//    public Observable<String> getErtcTokenDebug(final String userId, final String roomId){
//        if(ertcEngine != null) {
//            return Observable.create(emitter -> {
//                String rtcToken = ErtcGenerateTestUserSig.genTestUserSig(ertcTestAppIdDebug, ertcTestSecretDebug, userId, roomId);
//                TokenInfo tokenInfo = ertcEngine.getToken(userId, roomId, rtcToken);
//                if(tokenInfo != null) {
//                    ertcToken = tokenInfo.token;
//                    emitter.onNext(ertcToken);
//                } else {
//                    emitter.onError(new Exception("ERTC 获取token失败"));
//                }
//            });
//        }else {
//            return Observable.error(new Exception("请先初始化 ERTC"));
//        }
//    }

    public void release() {
        if (ertcEngine != null) {
            ERTCEngine.destroyEngine();
            ertcEngine = null;
        }
    }
}
