package com.huawei.rtcdemo;

import android.app.Application;
import android.content.SharedPreferences;

import com.huawei.rtc.IRtcEngineEventHandler;
import com.huawei.rtc.RtcEngine;
import com.huawei.rtc.models.LogInfo;
import com.huawei.rtcdemo.adapter.RtcEventHandler;
import com.huawei.rtcdemo.utils.KLog;
import com.huawei.rtcdemo.utils.PrefManager;

import static com.huawei.rtc.models.LogInfo.LogLevel.LOG_LEVEL_DEBUG;

public class RtcApplication extends Application {
    private RtcEngine mHwRtcEngine;
    private RtcEventHandler mHwHandler = new RtcEventHandler();
    String serverAddr;
    String appId;
    SharedPreferences rtcSp;

    public RtcApplication(){
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        rtcSp = PrefManager.getPreferences(getApplicationContext());
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        RtcEngine.destroy();
    }

    public RtcEngine getEngine() {
        if(mHwRtcEngine == null) {
            LogInfo logInfo = new LogInfo();
            logInfo.setLevel(LOG_LEVEL_DEBUG);
            logInfo.setPath(KLog.getLogPath());
            RtcEngine.setLogParam(true,logInfo);

            serverAddr = rtcSp.getString(Constants.RTC_PREF_SERVER_ADDR, Constants.RTC_DEFAULT_SERVER_ADDR);
            appId = Constants.RTC_DEFAULT_APP_ID;
            mHwRtcEngine = RtcEngine.create(getApplicationContext(), serverAddr, appId, mHwHandler);
        }

        return mHwRtcEngine;
    }

    public void registerEventHandler(IRtcEngineEventHandler handler) {
        mHwHandler.addHandler(handler);
    }

    public void removeEventHandler(IRtcEngineEventHandler handler) {
        mHwHandler.removeHandler(handler);
    }
}
