package com.android.chmo.im;

import android.util.Log;

import com.android.chmo.app.ChmoApplication;
import com.android.chmo.http.HttpApi;
import com.android.chmo.model.LoginUser;
import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.constant.UserInfoFieldEnum;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/8/8.
 */

public class IMManager {
    private final static String TAG = "IMManager";
    public static void login() {
        LoginInfo info = ChmoApplication.getApp().imLoginInfo();
        if(info == null){
            return;
        }
        Log.i(TAG, "==================== IMLogin  ===============  "+ info.getAccount() + "   " + info.getToken());
        NimUIKit.login(info, new com.netease.nimlib.sdk.RequestCallback<LoginInfo>() {

            @Override
            public void onSuccess(LoginInfo param) {
                Log.i(TAG, "IMLogin onSuccess ===============  " + param.toString());
                NimUIKit.loginSuccess(param.getAccount());
                AVChatKit.setAccount(param.getAccount());
                updateUser();
            }

            @Override
            public void onFailed(int code) {
                Log.e(TAG, "IMLogin onFailed ===============  " + code);
            }

            @Override
            public void onException(Throwable exception) {
                Log.e(TAG, "IMLogin onException ===============  " + exception.toString());
            }
        });
    }

    public static void updateUser() {
        LoginUser user = ChmoApplication.getApp().getLoginUser();
        Map<UserInfoFieldEnum, Object> fields = new HashMap<>(1);
        fields.put(UserInfoFieldEnum.Name, user.pet);
        fields.put(UserInfoFieldEnum.AVATAR, HttpApi.getImgUrl(user.hphoto));
        NIMClient.getService(UserService.class).updateUserInfo(fields)
                .setCallback(new RequestCallbackWrapper<Void>() {
                    @Override
                    public void onResult(int i, Void aVoid, Throwable throwable) {
                    }
                });
    }


    public static void logout() {
        NimUIKit.logout();
    }

}
