package tech.starwin.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;

import com.facebook.accountkit.AccountKitError;
import com.facebook.accountkit.AccountKitLoginResult;
import com.facebook.accountkit.ui.AccountKitActivity;
import com.facebook.accountkit.ui.AccountKitConfiguration;
import com.facebook.accountkit.ui.LoginType;

import java.util.List;

import tech.starwin.LibConfig;
import tech.starwin.mvp.beans.TokenInfoBean;
import tech.starwin.mvp.beans.UserBean;
import tech.starwin.utils.context_utils.EasyActivityResult;
import tech.starwin.utils.context_utils.ActivityJumper;

/**
 * Created by SiKang on 2018/9/19.
 * 登录数据管理
 */
public class LoginManager {
    public static final String TAG = "LoginManager";
    private static LoginManager loginManager;
    private TokenInfoBean tokenInfo;
    private UserBean userInfo;

    private LoginManager() {
    }

    public static LoginManager get() {
        if (loginManager == null) {
            synchronized (LoginManager.class) {
                if (loginManager == null) {
                    loginManager = new LoginManager();
                }
            }
        }
        return loginManager;
    }

    /**
     * token失效，需要重新登录
     */
    public void tokenInvalid() {
        //清除登录状态
        PreferencesManager.get().clearLoginInfo();
        tokenInfo = null;
        //跳转登录界面
        if (isActionSupport(LibConfig.getContext(), LibConfig.LOGIN_ACTIVITY_ACTION)) {
            new ActivityJumper.Builder(LibConfig.getContext(), LibConfig.LOGIN_ACTIVITY_ACTION)
                    .build().start();
        } else {
            LogUtils.e(TAG, "找不到LoginActivity，请在build.gradle中配置正确的 ‘LOGIN_ACTIVITY_ACTION’ ");
        }
    }


    /**
     * facebook 短信登录
     */
    public void startFacebookSmsLogin(FragmentActivity activity, final OnFacebookLoginResult result) {
        final Intent intent = new Intent(activity, AccountKitActivity.class);
        AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder =
                new AccountKitConfiguration.AccountKitConfigurationBuilder(
                        LoginType.PHONE,
                        AccountKitActivity.ResponseType.CODE); // or .ResponseType.TOKEN
        intent.putExtra(AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION, configurationBuilder.build());

        new EasyActivityResult(activity).startForResult(intent, 0, new EasyActivityResult.OnResultListener() {
            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (requestCode == 0) { // confirm that this response matches your request
                    AccountKitLoginResult loginResult = data.getParcelableExtra(AccountKitLoginResult.RESULT_KEY);
                    if (loginResult.getError() != null) {
                        result.onLoginError(loginResult.getError());
                    } else if (loginResult.wasCancelled()) {
                        result.onLoginCancelled();
                    } else {
                        result.onLoginSuccess(loginResult);
                    }

                }
            }
        });
    }


    /**
     * 刷新Token
     */
    public void notifyTokenInfo(TokenInfoBean tokenInfo) {
        this.tokenInfo = tokenInfo;
        PreferencesManager.get().saveTokenInfo(tokenInfo);
    }

    /**
     * 获取Token
     */
    public String getToken() {
        return getTokenInfo() == null ? "" : tokenInfo.getToken();
    }

    public TokenInfoBean getTokenInfo() {
        if (tokenInfo == null) {
            tokenInfo = PreferencesManager.get().getTokenInfo();
        }
        return tokenInfo;
    }

    /**
     * 获取用户信息
     */
    public UserBean getUserInfo() {
        if (userInfo == null) {
            userInfo = PreferencesManager.get().getUserInfo();
        }
        return userInfo;
    }


    /**
     * 退出登录
     */
    public void logout() {
        tokenInfo = null;
        PreferencesManager.get().clearLoginInfo();
    }


    public interface OnFacebookLoginResult {
        void onLoginSuccess(AccountKitLoginResult loginResult);

        void onLoginError(AccountKitError error);

        void onLoginCancelled();
    }


    /**
     * 是否存在某个可跳转的action
     */
    private boolean isActionSupport(Context context, String action) {
        final PackageManager packageManager = context.getPackageManager();
        final Intent intent = new Intent(action);
        List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        if (resolveInfo.size() > 0) {
            return true;
        }
        return false;
    }

}
