package com.yidianling.im.config;

import android.content.Context;
import android.graphics.Color;
import android.os.Environment;
import android.text.TextUtils;

import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.mixpush.MixPushConfig;
import com.netease.nimlib.sdk.msg.MessageNotifierCustomization;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.ydl.ydlcommon.base.BaseApp;
import com.ydl.ydlcommon.base.config.YDLConstants;
import com.ydl.ydlcommon.utils.YDLCacheUtils;
import com.yidianling.im.R;
import com.yidianling.im.api.bean.IMInitConfigBean;
import com.yidianling.im.config.constants.UserPreferences;
import com.yidianling.im.config.provider.CustomUserInfoProvider;
import com.yidianling.im.preference.IMCache;
import com.yidianling.uikit.api.wrapper.MessageRevokeTip;
import com.yidianling.uikit.business.session.viewholder.MsgViewHolderThumbBase;

import java.io.IOException;

/**
 * Created by hzchenkang on 2017/9/26.
 * <p>
 * 云信sdk 自定义的SDK选项设置
 */

class NimSDKOptionConfig {

    static SDKOptions prepareSDKOptions(Context context, Class activity, IMInitConfigBean configBean) {
        SDKOptions options  = new SDKOptions();
        //线上环境关闭
        if (BaseApp.Companion.getInstance().getGlobalConfig().getAppDebug()) {
            //配置检查
            options.checkManifestConfig = true;
        }
        options.appKey = getIMAppKey(configBean);

        // 如果将新消息通知提醒托管给SDK完成，需要添加以下配置。
        initStatusBarNotificationConfig(context, options, activity);

        // 配置 APP 保存图片/语音/文件/log等数据的目录
        options.sdkStorageRootPath = getAppCacheDir(context) + "/yidianling"; // 可以不设置，那么将采用默认路径


        // 配置是否需要预下载附件缩略图
        options.preloadAttach = true;

        // 配置附件缩略图的尺寸大小
        options.thumbnailSize = MsgViewHolderThumbBase.getImageMaxEdge();

        // 通知栏显示用户昵称和头像
        options.userInfoProvider = new CustomUserInfoProvider(IMCache.getContext());

        // 定制通知栏提醒文案（可选，如果不定制将采用SDK默认文案）
        options.messageNotifierCustomization = messageNotifierCustomization;

        // 在线多端同步未读数
        options.sessionReadAck = true;

        // 动图的缩略图直接下载原图
        options.animatedImageThumbnailEnabled = true;
        // 采用异步加载SDK
        options.asyncInitSDK = true;

        // 是否是弱IM场景
        options.reducedIM = false;

        // 是否检查manifest 配置，调试阶段打开，调试通过之后请关掉
        options.checkManifestConfig = false;

        // 是否启用群消息已读功能，默认关闭
        options.enableTeamMsgAck = true;

        // 打开消息撤回未读数-1的开关
        options.shouldConsiderRevokedMessageUnreadCount = true;

        options.mixPushConfig = buildMixPushConfig(configBean);

        return options;
    }


    /**
     * 配置 APP 保存图片/语音/文件/log等数据的目录
     * 这里示例用SD卡的应用扩展存储目录
     */
    static String getAppCacheDir(Context context) {
        String storageRootPath = null;
        try {
            // SD卡应用扩展存储区(APP卸载后，该目录下被清除，用户也可以在设置界面中手动清除)，请根据APP对数据缓存的重要性及生命周期来决定是否采用此缓存目录.
            // 该存储区在API 19以上不需要写权限，即可配置 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18"/>
            if (context.getExternalCacheDir() != null) {
                storageRootPath = context.getExternalCacheDir().getCanonicalPath();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (TextUtils.isEmpty(storageRootPath)) {
            // SD卡应用公共存储区(APP卸载后，该目录不会被清除，下载安装APP后，缓存数据依然可以被加载。SDK默认使用此目录)，该存储区域需要写权限!
            storageRootPath = Environment.getExternalStorageDirectory() + "/" + IMCache.getContext().getPackageName();
        }

        return storageRootPath;
    }

    private static void initStatusBarNotificationConfig(Context context, SDKOptions options, Class activity) {
        // load 应用的状态栏配置
        StatusBarNotificationConfig config = loadStatusBarNotificationConfig(context, activity);

        // load 用户的 StatusBarNotificationConfig 设置项
        StatusBarNotificationConfig userConfig = UserPreferences.getStatusConfig();
        if (userConfig == null) {
            userConfig = config;
        } else {
            // 新增的 UserPreferences 存储项更新，兼容 3.4 及以前版本
            // 新增 notificationColor 存储，兼容3.6以前版本
            // APP默认 StatusBarNotificationConfig 配置修改后，使其生效
            userConfig.notificationEntrance = config.notificationEntrance;
            userConfig.notificationFolded = config.notificationFolded;
            userConfig.notificationColor = config.notificationColor;
        }
        // 持久化生效
        UserPreferences.setStatusConfig(userConfig);
        // SDK statusBarNotificationConfig 生效
        options.statusBarNotificationConfig = userConfig;
    }

    // 这里开发者可以自定义该应用初始的 StatusBarNotificationConfig
    private static StatusBarNotificationConfig loadStatusBarNotificationConfig(Context context, Class activity) {
        StatusBarNotificationConfig config = new StatusBarNotificationConfig();
        // 点击通知需要跳转到的界面
        config.notificationEntrance = activity;
        config.notificationSmallIconId = R.mipmap.im_ic_launcher;
        config.notificationColor = IMCache.getContext().getResources().getColor(R.color.platform_color_blue_3a9efb);
        // 通知铃声的uri字符串
//        config.notificationSound = "android.resource://com.yidianling.im/raw/msg";
        String SoundUri = "android.resource://" + context.getPackageName() + "/" + R.raw.im_msg;

        config.notificationSound = SoundUri;
        config.notificationFolded = true;
        // 呼吸灯配置
        config.ledARGB = Color.GREEN;
        config.ledOnMs = 1000;
        config.ledOffMs = 1500;
        config.ring = true;
        config.vibrate = true;
        // 是否APP ICON显示未读数红点(Android O有效)
        config.showBadge = true;

        // save cache，留做切换账号备用
        IMCache.setNotificationConfig(config);
        return config;
    }

    private static MessageNotifierCustomization messageNotifierCustomization = new MessageNotifierCustomization() {
        @Override
        public String makeNotifyContent(String nick, IMMessage message) {
            return null; // 采用SDK默认文案
        }

        @Override
        public String makeTicker(String nick, IMMessage message) {
            return null; // 采用SDK默认文案
        }

        @Override
        public String makeRevokeMsgTip(String revokeAccount, IMMessage item) {
            return MessageRevokeTip.getRevokeTipContent(item, revokeAccount);
        }
    };


    private static String getIMAppKey(IMInitConfigBean configBean) {
        String debugKey = "9a8cefe97b7690537fc1334091af9208";
        String releaseKey = "4e258ba5cdf489fa188274ebf0fb5669";
        String finalKey  = "";

        if(configBean!=null&&!TextUtils.isEmpty(configBean.debugAppKey)&&!TextUtils.isEmpty(configBean.releaseAppKey)) {
            debugKey = configBean.debugAppKey;
            releaseKey = configBean.releaseAppKey;
        }

        //key配置---逻辑更改：修复切换环境功能
        if (BaseApp.Companion.getInstance().getGlobalConfig().getAppDebug()) {
            String appEnv = BaseApp.Companion.getInstance().getGlobalConfig().getAppEnv();

            //debug包根据url判断使用正式或者测试key
            String cacheAppEnv = YDLCacheUtils.Companion.getCacheApi();

            if (!TextUtils.isEmpty(cacheAppEnv)) {
                appEnv = cacheAppEnv;
            }

            if (YDLConstants.ENV_TEST.equals(appEnv)|| YDLConstants.ENV_AUTO_TEST.equals(appEnv)) {
                finalKey = debugKey;
            } else {
                finalKey = releaseKey;
            }

        } else {
            //release包始终使用正式key
            finalKey = releaseKey;
        }

        return finalKey;
    }
    private static MixPushConfig buildMixPushConfig(IMInitConfigBean configBean) {

        // 第三方推送配置
        MixPushConfig config = new MixPushConfig();

        if(configBean!=null && !TextUtils.isEmpty(configBean.hwCertificateName)) {
            // 小米推送
            config.xmAppId = splitString(configBean.xmAppId);
            config.xmAppKey = splitString(configBean.xmAppKey);
            config.xmCertificateName = splitString(configBean.xmCertificateName);
            //魅族
            config.mzAppId = splitString(configBean.mzAppId);
            config.mzAppKey = splitString(configBean.mzAppKey);
            config.mzCertificateName = splitString(configBean.mzCertificateName);
            // 华为推送
            config.hwAppId = splitString(configBean.hwAppId);
            config.hwCertificateName = splitString(configBean.hwCertificateName);
            //OPPO 推送
            config.oppoAppId = splitString(configBean.oppoAppId);
            config.oppoAppKey = splitString(configBean.oppoAppKey);
            config.oppoAppSercet = splitString(configBean.oppoAppSercet);
            config.oppoCertificateName = splitString(configBean.oppoCertificateName);
            //VIVO 推送
            config.vivoCertificateName = splitString(configBean.vivoCertificateName);

        } else {
            String appFrom = BaseApp.Companion.getInstance().getGlobalConfig().getAppFrom();
            if (YDLConstants.FROM_YDL.equals(appFrom) || YDLConstants.FROM_YDL2.equals(appFrom)) {
                // 小米推送
                config.xmAppId = "2882303761517432980";
                config.xmAppKey = "5241743243980";
                config.xmCertificateName = "ydlUser";
                // 华为推送
                config.hwCertificateName = "ydlUserHw";
                //OPPO 推送
                config.oppoAppId = "3245516";
                config.oppoAppKey = "afk71f35VogGw0w0wKsookksc";
                config.oppoAppSercet = "691184F044acA7a6851F578451f67616";
                config.oppoCertificateName = "ydlUserOPPO";
                //VIVO 推送
                config.vivoCertificateName = "ydlUserVIVO";
            } else if(YDLConstants.FROM_XLZX.equals(appFrom)) {
                // 小米推送
                config.xmAppId = "2882303761517549919";
                config.xmAppKey = "5111754949919";
                config.xmCertificateName = "ydlXLZXXM";
                // 华为推送
                config.hwCertificateName = "ydlXLZX";
                //OPPO 推送
                config.oppoAppId = "3601521";
                config.oppoAppKey = "c500cJ5mzvSow848048gOsG4G";
                config.oppoAppSercet = "F13EbCf4380b683Fb0e316336eeC9Deb";
                config.oppoCertificateName = "ydlXLZXOPPO";
                //VIVO 推送
                config.vivoCertificateName = "ydlXLZXVIVO";
            }
        }

        return config;
    }

    private static String splitString(String string) {
        if(string.contains("-")) {
            string = string.substring(string.lastIndexOf("-")+1);
        }
        return string;
    }
}
