package com.mogo.cloud.passport.internal;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.mogo.cloud.passport.IPassport;
import com.mogo.cloud.passport.MoGoAiCloudClient;
import com.mogo.cloud.passport.MoGoAiCloudClientConfig;
import com.mogo.cloud.passport.utils.DevicesUtils;
import com.zhidao.account.sdk.AccountClientManager;
import com.zhidao.account.sdk.BusinessType;
import com.zhidao.account.sdk.Environment;
import com.zhidao.account.sdk.callback.TicketInfoCallback;

import static com.mogo.cloud.passport.MoGoAiCloudClient.TAG;
import static com.mogo.cloud.passport.MoGoAiCloudClientConfig.HTTP_DNS_ENV_DEV;
import static com.mogo.cloud.passport.MoGoAiCloudClientConfig.HTTP_DNS_ENV_QA;

public class InternalPassportManager {

    private static volatile InternalPassportManager mInstance;
    private IPassport mPassport;
    private final MoGoAiCloudClientConfig mAiCloudClientConfig;

    private InternalPassportManager(Context context) {
        mAiCloudClientConfig = MoGoAiCloudClient.getInstance().getAiCloudClientConfig();
        String appId = mAiCloudClientConfig.getServiceAppId();
        if (TextUtils.isEmpty(appId)) {
            Log.e(TAG, "需要初始化 passport AppId");
            return;
        }
        AccountClientManager.init(context.getApplicationContext(), getNetEnvironment(), BusinessType.toc_login, appId);
    }

    public static InternalPassportManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (InternalPassportManager.class) {
                if (mInstance == null) {
                    mInstance = new InternalPassportManager(context);
                }
            }
        }
        return mInstance;
    }

    public void refreshToken(IPassport passport) {
        this.mPassport = passport;
        AccountClientManager.getTicket(new TicketInfoCallback() {
            @Override
            public void onSuccess(String ticket) {
                if (mPassport != null) {
                    mPassport.onSuccess(ticket, DevicesUtils.getSn());
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                if (mPassport != null) {
                    mPassport.onError(code, msg);
                }
            }
        });
    }

    /**
     * 演示环境(SHOW环境)和线上环境(RELEASE)均走 Environment.release
     * @return {@link Environment}
     */
    private Environment getNetEnvironment() {
        int mode = mAiCloudClientConfig.getNetMode();
        Environment environment;
        switch (mode) {
            case HTTP_DNS_ENV_DEV:
                environment = Environment.dev;
                break;
            case HTTP_DNS_ENV_QA:
                environment = Environment.qa;
                break;
            default:
                environment = Environment.release;
                break;
        }
        return environment;
    }
}
