package com.yidianling.im.config;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import androidx.annotation.DrawableRes;

import com.alibaba.fastjson.JSON;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.mixpush.MixPushMessageHandler;
import com.netease.nimlib.sdk.mixpush.NIMPushClient;
import com.netease.nimlib.sdk.uinfo.model.UserInfo;
import com.netease.nimlib.sdk.util.NIMUtil;
import com.ydl.ydlcommon.utils.SharedPreferencesEditor;
import com.yidianling.avchatkit.AVChatKit;
import com.yidianling.avchatkit.config.AVChatOptions;
import com.yidianling.avchatkit.model.ITeamDataProvider;
import com.yidianling.avchatkit.model.IUserInfoProvider;
import com.yidianling.im.R;
import com.yidianling.im.api.bean.IMInitConfigBean;
import com.yidianling.im.api.event.AccountChangeEvent;
import com.yidianling.im.config.constants.UserPreferences;
import com.yidianling.im.helper.ImObserversHelper;
import com.yidianling.im.helper.NIMInitManager;
import com.yidianling.im.preference.IMCache;
import com.yidianling.im.router.ImIn;
import com.yidianling.im.session.SessionHelper;
import com.yidianling.nimbase.api.UIKitOptions;
import com.yidianling.uikit.api.NimUIKit;
import com.yidianling.uikit.business.team.helper.TeamHelper;
import com.yidianling.uikit.business.uinfo.UserInfoHelper;
import com.yidianling.uikit.custom.config.YDLToolBarOptions;
import com.yidianling.user.api.bean.UserResponseBean;

import java.util.Map;

import de.greenrobot.event.EventBus;


public class NimApplication {
    private String appKey;

    private NimApplication() {
    }

    private static class InstanceHolder {
        static NimApplication nimApplication = new NimApplication();
    }

    public static NimApplication getInstance() {
        return InstanceHolder.nimApplication;
    }

    public String getAppKey() {
        return appKey;
    }

    public void initIm(Application app, Class activity, IMInitConfigBean configBean) {
        IMCache.setContext(app);
        // 初始化云信SDK
        SDKOptions sdkOptions = NimSDKOptionConfig.prepareSDKOptions(app, activity, configBean);
        appKey = sdkOptions.appKey;
        NIMClient.init(app, loginInfo(), sdkOptions);

        // 以下逻辑只在主进程初始化时执行
        if (NIMUtil.isMainProcess(app)) {
            // 初始化UIKit模块
            initUIKit(app);
            // 初始化消息提醒
            NIMClient.toggleNotification(UserPreferences.getNotificationToggle());
            // 云信sdk相关业务初始化
            NIMInitManager.getInstance().init(true);
            // 初始化音视频模块
            initAVChatKit(activity, configBean.notificationIconRes);
            //注册状态观察者
            ImObserversHelper.Companion.getInstance().registerObserver(true);
            // 初始化听筒模式
            initEarMode();
            NIMPushClient.registerMixPushMessageHandler(new MixPushMessageHandler() {
                @Override
                public boolean onNotificationClicked(Context context, Map<String, String> map) {
                    Log.d("notification", JSON.toJSONString(map));
                    String routeAndroid = map.get("route_android");
                    if (routeAndroid != null) {
                        try {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setPackage(context.getPackageName());
                            intent.setData(Uri.parse(routeAndroid));
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context.startActivity(intent);
                            return true;
                        } catch (Throwable e) {
                            Log.e("app", "", e);
                        }
                    }
                    return false;
                }

                @Override
                public boolean cleanMixPushNotifications(int i) {
                    return false;
                }
            });
        }
    }

    // 如果已经存在用户登录信息，返回LoginInfo，否则返回null即可
    private LoginInfo loginInfo(){
        UserResponseBean loginBean = ImIn.INSTANCE.getUserResponse();
       if(loginBean != null) {
            IMCache.setAccount(loginBean.getUid());
       }
        return loginBean != null? new LoginInfo(loginBean.getUid(), loginBean.getHxpwd()) : null;

    }

    private void initUIKit(Application application) {
        // 初始化
        NimUIKit.init(application, buildUIKitOptions(application));

        // IM 会话窗口的定制初始化。
        SessionHelper.init();
    }

    private UIKitOptions buildUIKitOptions(Application application) {
        UIKitOptions options = new UIKitOptions();
        // 设置app图片/音频/日志等缓存目录
        options.appCacheDir = NimSDKOptionConfig.getAppCacheDir(application) + "/app";
        //options.buildNimUserCache = true;
        options.shouldHandleReceipt = true;
        options.toolBarOptions = new YDLToolBarOptions();
        options.messageLeftBackground = R.drawable.im_message_receive_content_bg;
        options.messageRightBackground = R.drawable.im_custom_message_round_1da1f2_6dp_bg;
        return options;
    }

    private void initAVChatKit(Class activity, @DrawableRes int notificationIconRes) {
        AVChatOptions avChatOptions = new AVChatOptions() {
            @Override
            public void logout(Context context) {
                EventBus.getDefault().post(new AccountChangeEvent(1));
            }
        };
        avChatOptions.entranceActivity = activity;
        avChatOptions.notificationIconRes = notificationIconRes;
        AVChatKit.init(avChatOptions);

        // 设置用户相关资料提供者
        AVChatKit.setUserInfoProvider(new IUserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String account) {
                return NimUIKit.getUserInfoProvider().getUserInfo(account);
            }

            @Override
            public String getUserDisplayName(String account) {
                return UserInfoHelper.getUserDisplayName(account);
            }
        });
        // 设置群组数据提供者
        AVChatKit.setTeamDataProvider(new ITeamDataProvider() {
            @Override
            public String getDisplayNameWithoutMe(String teamId, String account) {
                return TeamHelper.getDisplayNameWithoutMe(teamId, account);
            }

            @Override
            public String getTeamMemberDisplayName(String teamId, String account) {
                return TeamHelper.getTeamMemberDisplayName(teamId, account);
            }
        });
    }

    public static final String EAR_MODE_OPEN = "1";
    public static final String EAR_MODE_CLOSE = "2";
    public static final String EAR_MODE_KEY = "EarMode";
    private void initEarMode() {
        String earMode = SharedPreferencesEditor.getString(EAR_MODE_KEY);
        if (!EAR_MODE_OPEN.equals(earMode) && !EAR_MODE_CLOSE.equals(earMode)) {
            //设置默认听筒模式 关闭
            ImIn.INSTANCE.updateEarMode(false);
        }
    }

}
