package com.android.chmo.app;

import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.text.TextUtils;

import com.android.chmo.R;
import com.android.chmo.base.BaseApplication;
import com.android.chmo.im.SessionHelper;
import com.android.chmo.im.location.ChmoLocationProvider;
import com.android.chmo.mixpush.ChmoMixPushMessageHandler;
import com.android.chmo.model.LoginUser;
import com.android.chmo.receiver.VChatReceiver;
import com.android.chmo.ui.activity.WelcomeActivity;
import com.android.chmo.utils.LoginUtils;
import com.android.chmo.utils.NotifyUtils;
import com.android.chmo.utils.PixelUtils;
import com.android.chmo.utils.crash.AppCrashHandler;
import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nim.avchatkit.config.AVChatOptions;
import com.netease.nim.avchatkit.model.ITeamDataProvider;
import com.netease.nim.avchatkit.model.IUserInfoProvider;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.UIKitOptions;
import com.netease.nim.uikit.business.team.helper.TeamHelper;
import com.netease.nim.uikit.business.uinfo.UserInfoHelper;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.mixpush.MixPushConfig;
import com.netease.nimlib.sdk.mixpush.NIMPushClient;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.uinfo.UserInfoProvider;
import com.netease.nimlib.sdk.uinfo.model.UserInfo;
import com.netease.nimlib.sdk.util.NIMUtil;

import java.io.IOException;

/**
 * Created by Administrator on 2018/7/30.
 */

public class ChmoApplication extends BaseApplication {
    private static ChmoApplication app;
    private LoginUser loginUser;
    private String code; // 验证码
    public static boolean isInit;

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;

        SpManager.getInstance().init(getApplicationContext());

        AppCrashHandler.getInstance(this);

        // SDK初始化（启动后台服务，若已经存在用户登录信息， SDK 将完成自动登录）
        NIMClient.init(this, imLoginInfo(), options());

        if (NIMUtil.isMainProcess(this)) {

            NIMPushClient.registerMixPushMessageHandler(new ChmoMixPushMessageHandler());

            initUIKit();
            // 初始化消息提醒
            NIMClient.toggleNotification(true);
            // 初始化音视频模块
            initAVChatKit();
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction("android.chmo.action.CALL");
        filter.addAction("android.chmo.action.INCOMING");
        filter.addAction("android.chmo.action.BEGIN_VIDEO");
        filter.addAction("android.chmo.action.END_VIDEO");
        VChatReceiver receiver = new VChatReceiver();
        registerReceiver(receiver, filter);
    }

    public static ChmoApplication getApp() {
        return app;
    }

    public void setLoginUser(LoginUser user) {
        loginUser = user;
    }

    public LoginUser getLoginUser() {
        if (null == loginUser) {
            loginUser = LoginUtils.getLoginUser();
        }
        return loginUser;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getCode() {
        return this.code;
    }


    private SDKOptions options() {
        SDKOptions options = new SDKOptions();

        // 如果将新消息通知提醒托管给 SDK 完成，需要添加以下配置。否则无需设置。
        StatusBarNotificationConfig config = new StatusBarNotificationConfig();
        config.notificationEntrance = WelcomeActivity.class; // 点击通知栏跳转到该Activity
        config.notificationSmallIconId = R.mipmap.ic_launcher;
        config.showBadge = true;
        // 呼吸灯配置
        config.ledARGB = Color.GREEN;
        config.ledOnMs = 1000;
        config.ledOffMs = 1500;
        // 通知铃声的uri字符串
        config.notificationSound = "android.resource://com.netease.nim.demo/raw/msg";
        options.statusBarNotificationConfig = config;

        // 配置保存图片，文件，log 等数据的目录
        // 如果 options 中没有设置这个值，SDK 会使用采用默认路径作为 SDK 的数据目录。
        // 该目录目前包含 log, file, image, audio, video, thumb 这6个目录。
        String sdkPath = getAppCacheDir(getApplicationContext()) + "/nim"; // 可以不设置，那么将采用默认路径
        // 如果第三方 APP 需要缓存清理功能， 清理这个目录下面个子目录的内容即可。
        options.sdkStorageRootPath = sdkPath;

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

        // 配置附件缩略图的尺寸大小。表示向服务器请求缩略图文件的大小
        // 该值一般应根据屏幕尺寸来确定， 默认值为 Screen.width / 2
        options.thumbnailSize = PixelUtils.getWindowWidth() / 2;

        // 用户资料提供者, 目前主要用于提供用户资料，用于新消息通知栏中显示消息来源的头像和昵称
        options.userInfoProvider = new UserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String account) {
                return NimUIKit.getUserInfoProvider().getUserInfo(account);
            }

            @Override
            public String getDisplayNameForMessageNotifier(String account, String sessionId,
                                                           SessionTypeEnum sessionType) {
                return UserInfoHelper.getUserDisplayName(account);
            }

            @Override
            public Bitmap getAvatarForMessageNotifier(SessionTypeEnum sessionType, String sessionId) {
                Bitmap bm = null;
                int defResId = R.drawable.nim_avatar_default;
                if (SessionTypeEnum.P2P == sessionType) {
                    UserInfo user = NimUIKit.getUserInfoProvider().getUserInfo(sessionId);
                    bm = (user != null) ? NimUIKit.getImageLoaderKit().getNotificationBitmapFromCache(user.getAvatar()) : null;
                }
                if (bm == null) {
                    Drawable drawable = getResources().getDrawable(defResId);
                    if (drawable instanceof BitmapDrawable) {
                        bm = ((BitmapDrawable) drawable).getBitmap();
                    }
                }
                return bm;
            }
        };

        options.mixPushConfig = buildMixPushConfig();
        return options;
    }

    // 如果已经存在用户登录信息，返回LoginInfo，否则返回null即可
    public LoginInfo imLoginInfo() {
        loginUser = LoginUtils.getLoginUser();
        if (loginUser == null) {
            return null;
        }
        LoginInfo info = new LoginInfo(loginUser.pk, loginUser.token);
        return info;
    }

    /**
     * 配置 APP 保存图片/语音/文件/log等数据的目录
     * 这里示例用SD卡的应用扩展存储目录
     */
    public 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() + "/" + context.getPackageName();
        }

        return storageRootPath;
    }


    private void initUIKit() {
        // 初始化
        NimUIKit.init(this, buildUIKitOptions());
        LoginInfo info = imLoginInfo();
        if (null != info) {
            NimUIKit.setAccount(info.getAccount());
        }

        // 设置地理位置提供者。如果需要发送地理位置消息，该参数必须提供。如果不需要，可以忽略。
        NimUIKit.setLocationProvider(new ChmoLocationProvider());
//        // IM 会话窗口的定制初始化。
        SessionHelper.init();

        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(new Observer<CustomNotification>() {
            @Override
            public void onEvent(CustomNotification message) {
                String content = message.getContent();
                if (content.contains("完成")) {
                    new NotifyUtils(getApplicationContext()).showOrderNotification("订单已完成", "订单已完成", message.getContent(), message.hashCode());
                } else {
                    new NotifyUtils(getApplicationContext()).showOrderNotification("模特已接单", "模特已接单", message.getContent(), message.hashCode());
                }
            }
        }, true);
    }

    private UIKitOptions buildUIKitOptions() {
        UIKitOptions options = new UIKitOptions();
        // 设置app图片/音频/日志等缓存目录
        options.appCacheDir = getAppCacheDir(this) + "/app";
        return options;
    }

    private void initAVChatKit() {
        AVChatOptions avChatOptions = new AVChatOptions() {
            @Override
            public void logout(Context context) {
                //被踢出
            }
        };
        avChatOptions.entranceActivity = WelcomeActivity.class;
        avChatOptions.notificationIconRes = R.mipmap.ic_launcher;
        AVChatKit.init(avChatOptions);
        AVChatKit.setContext(getApplicationContext());
        LoginInfo info = imLoginInfo();
        if (null != info) {
            AVChatKit.setAccount(info.getAccount());
        }

        // 初始化日志系统
//        LogHelper.init();
        // 设置用户相关资料提供者
        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);
            }
        });

    }


    private static MixPushConfig buildMixPushConfig() {

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

        // 小米推送
        config.xmAppId = "2882303761517852623";
        config.xmAppKey = "5401785275623";
        config.xmCertificateName = "MIPUSH";

        // 华为推送
        config.hwCertificateName = "HUAWEIPUSH";

        // 魅族推送
        config.mzAppId = "1001752";
        config.mzAppKey = "8082e4724ca34784a1f28e04b770661a";
        config.mzCertificateName = "MEZUPUSH";


        return config;
    }
}
