package com.mogo.cloud.passport;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Keep;

import java.util.ArrayList;
import java.util.List;

/**
 * 蘑菇AI云平台SDK入口
 *
 * @author donghongyu
 */
@Keep
public class MoGoAiCloudClient {
    public static final String TAG = "MoGoAiCloudClient";
    private static volatile MoGoAiCloudClient sInstance;

    private MoGoAiCloudClientConfig mAiCloudClientConfig;
    private Context mContext;

    private final List<IMoGoTokenCallback> mTokenCallbacks;

    private MoGoAiCloudClient() {
        mTokenCallbacks = new ArrayList<>();
    }

    @Keep
    public static MoGoAiCloudClient getInstance() {
        if (sInstance == null) {
            synchronized (MoGoAiCloudClient.class) {
                if (sInstance == null) {
                    sInstance = new MoGoAiCloudClient();
                }
            }
        }
        return sInstance;
    }

    /**
     * 初始化
     *
     * @param context             上下文
     * @param aiCloudClientConfig SDK配置信息
     */
    public MoGoAiCloudClient init(Context context,
                                  MoGoAiCloudClientConfig aiCloudClientConfig
    ) {
        mContext = context;
        mAiCloudClientConfig = aiCloudClientConfig;
        // 控制日志输出
        if (!mAiCloudClientConfig.isShowDebugLog()) {
            // 关闭鉴权模块的日志
            com.zhidao.account.sdk.utils.Logger.init(false);
            // 关闭所有SDK中的日志
            com.elegant.log.simplelog.Logger.init(com.elegant.log.simplelog.LogLevel.OFF);
        }
        // 刷新令牌
        refreshToken();
        return sInstance;
    }

    public Context getContext() {
        return mContext;
    }

    public MoGoAiCloudClientConfig getAiCloudClientConfig() {
        return mAiCloudClientConfig;
    }

    public void refreshToken() {
        Log.i(TAG, "═══════════════刷新Token═════════════");

        PassportManager.getInstance().refreshToken(mContext, new IPassport() {
            @Override
            public void onSuccess(String token, String sn) {
                Log.i(TAG, "═════════════════════════════════════");
                Log.i(TAG, "║ PassportVersion：" + com.mogo.cloud.passport.BuildConfig.VERSION_NAME);
                Log.i(TAG, "║ ThirdLoginVersion：" + com.zhidao.thirdlogin.BuildConfig.VERSION_NAME);
                Log.i(TAG, "║ MoGo鉴权成功 ");
                Log.i(TAG, "║ SN：" + sn);
                Log.i(TAG, "║ Token：" + token);
                Log.i(TAG, "═════════════════════════════════════");

                // 变量赋值
                if (mAiCloudClientConfig != null) {
                    mAiCloudClientConfig.setSn(sn);
                    mAiCloudClientConfig.setToken(token);
                }

                //  循环调用将数据传出去
                for (IMoGoTokenCallback tokenCallback : mTokenCallbacks) {
                    tokenCallback.onTokenGot(token, sn);
                }
            }

            @Override
            public void onError(int code, String msg) {
                Log.e(TAG, "═════════════════════════════════════");
                Log.e(TAG, "║ MoGo鉴权失败 ");
                Log.e(TAG, "║ ErrorCode：" + code);
                Log.e(TAG, "║ ErrorMessage：" + msg);
                Log.e(TAG, "═════════════════════════════════════");

                //如果本地sp缓存中存在sn和token，防止在鉴权失败后引起ERROR重置本地缓存
                if (mAiCloudClientConfig.getSn() != null
                        && !mAiCloudClientConfig.getSn().isEmpty()
                        && mAiCloudClientConfig.getToken() != null
                        && !mAiCloudClientConfig.getToken().isEmpty()) {
                    return;
                }

                if (mAiCloudClientConfig.isShowToastLog()) {
                    Toast.makeText(mContext, "首次鉴权失败，本地无历史缓存SN，请检查「设备时间」和「网络」", Toast.LENGTH_SHORT).show();
                }

                // 变量赋值
                if (mAiCloudClientConfig != null) {
                    mAiCloudClientConfig.setSn("");
                    mAiCloudClientConfig.setToken("");
                }
                for (IMoGoTokenCallback tokenCallback : mTokenCallbacks) {
                    tokenCallback.onError(code, msg);
                }
            }
        });
    }

    /**
     * 添加Token 回调
     *
     * @param iMoGoTokenCallback 回调监听
     */
    public void addTokenCallbacks(IMoGoTokenCallback iMoGoTokenCallback) {
        mTokenCallbacks.add(iMoGoTokenCallback);
    }

}
