package tr.dhee.abox.demo.data;

import tr.dhee.abox.demo.data.model.LoggedInUser;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Class that requests authentication and user information from the remote data source and
 * maintains an in-memory cache of login status and user credentials information.
 * 登录在后台线程执行(SDK 的 loginWithUsername 是同步网络调用, 不能在主线程跑, 否则 ANR)。
 */
public class LoginRepository {

    private static volatile LoginRepository instance;

    private LoginDataSource dataSource;
    private final Executor executor = Executors.newSingleThreadExecutor();

    // If user credentials will be cached in local storage, it is recommended it be encrypted
    // @see https://developer.android.com/training/articles/keystore
    private LoggedInUser user = null;

    // private constructor : singleton access
    private LoginRepository(LoginDataSource dataSource) {
        this.dataSource = dataSource;
    }

    public static LoginRepository getInstance(LoginDataSource dataSource) {
        if (instance == null) {
            instance = new LoginRepository(dataSource);
        }
        return instance;
    }

    public boolean isLoggedIn() {
        return user != null;
    }

    public void logout() {
        user = null;
        dataSource.logout();
    }

    private void setLoggedInUser(LoggedInUser user) {
        this.user = user;
        // If user credentials will be cached in local storage, it is recommended it be encrypted
        // @see https://developer.android.com/training/articles/keystore
    }

    public void login(String username, String password, LoginCallback callback) {
        executor.execute(() -> {
            Result<LoggedInUser> result = dataSource.login(username, password);
            if (result instanceof Result.Success) {
                setLoggedInUser(((Result.Success<LoggedInUser>) result).getData());
            }
            if (callback != null) {
                callback.onComplete(result);
            }
        });
    }

    public interface LoginCallback {
        void onComplete(Result<LoggedInUser> result);
    }
}
