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 android.util.Base64;

import com.facebook.accountkit.AccountKit;
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 org.greenrobot.eventbus.EventBus;

import java.util.List;

import tech.starwin.LibConfig;
import tech.starwin.R;
import tech.starwin.constants.ActionEnum;

import com.common.bean.TokenInfoBean;
import com.common.bean.UserBean;

import tech.starwin.utils.context_utils.EasyActivityResult;
import tech.starwin.utils.format_utils.StringFormat;

/**
 * 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;
        //广播通知
        EventBus.getDefault().post(ActionEnum.LOGIN_INVALID);

//        if (!TextUtils.isEmpty(LibConfig.LOGIN_ACTIVITY_ACTION)) {
//            //跳转登录界面
//            if (isActionSupport(LibConfig.getActivity(), LibConfig.LOGIN_ACTIVITY_ACTION)) {
//                new ActivityJumper.Builder(LibConfig.getActivity(), 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) {
        if (AccountKit.getCurrentAccessToken() != null) {
            AccountKit.logOut();
        }
        String[] countryCodes;
        if (LibConfig.DEBUG) {
            countryCodes = new String[]{"CN", "ID"};
        } else {
            countryCodes = new String[]{"ID"};
        }

        final Intent intent = new Intent(activity, AccountKitActivity.class);
        AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder =
                new AccountKitConfiguration.AccountKitConfigurationBuilder(
                        LoginType.PHONE,
                        AccountKitActivity.ResponseType.CODE)
                        .setInitialAuthState(generateRandomString())
                        .setFacebookNotificationsEnabled(true)
                        .setSMSWhitelist(countryCodes)
                        .setDefaultCountryCode("ID"); // 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 && data != null) { // confirm that this response matches your request
                    AccountKitLoginResult loginResult = data.getParcelableExtra(AccountKitLoginResult.RESULT_KEY);
                    if (loginResult == null) {
                        result.onLoginError(new AccountKitError(AccountKitError.Type.INITIALIZATION_ERROR));
                    } else if (loginResult.getError() != null) {
                        result.onLoginError(loginResult.getError());
                    } else if (loginResult.wasCancelled()) {
                        result.onLoginCancelled();
                    } else {
                        result.onLoginSuccess(loginResult);
                    }
                }else{
                    result.onLoginError(new AccountKitError(AccountKitError.Type.INITIALIZATION_ERROR));
                }
            }
        });

    }

    private String generateRandomString() {
        double randomNum = Math.random();
        long currentTime = System.currentTimeMillis();
        return StringFormat.base64((LibConfig.APPLICATION_ID + randomNum + currentTime).getBytes(), Base64.DEFAULT);
    }


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

    /**
     * 获取Token
     */
    public String getToken() {
        //需要用客户的token测试时使用
        if (!TextUtils.isEmpty(LibConfig.TEST_TOKEN)) {
            return LibConfig.TEST_TOKEN;
        }
        return getTokenInfo() == null ? "" : getTokenInfo().getToken();
    }

    /**
     * 获取手机号
     */
    public String getMobile() {
        String mobile = getTokenInfo() == null ? "" : getTokenInfo().getMobile();
        return mobile == null ? "" : mobile;
    }

    /**
     * 获取用户名
     */
    public String getUserName() {
        return getUserInfo() == null ? "" : getUserInfo().getName();
    }

    public TokenInfoBean getTokenInfo() {
        if (!TextUtils.isEmpty(LibConfig.TEST_TOKEN)) {
            return new TokenInfoBean();
        }
        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;
        userInfo = null;
        PreferencesManager.get().clearLoginInfo();
        AccountKit.logOut();
    }


    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;
    }

}
