package tr.dhee.abox.demo.data;

import tr.dhee.abox.demo.data.model.LoggedInUser;
import tr.dhee.abox.demo.utils.AboxConstants;
import com.dhc.absdk.ABRet;
import com.dhc.absdk.ABSDK;

import java.io.IOException;

/**
 * Class that handles authentication w/ login credentials and retrieves user information.
 * 接 base 真登录: 调用 libABSDK0630.jar 的 ABSDK.getInstance().loginWithUsername()。
 */
public class LoginDataSource {

    public Result<LoggedInUser> login(String username, String password) {

        try {
            // base 登录核心: 同步阻塞网络调用, 在 LoginRepository 的后台线程执行(不会 ANR)
            ABRet abRet = ABSDK.getInstance().loginWithUsername(username, password);
            if (abRet != null && "00000".equals(abRet.getCode())) {
                // 成功: 用用户名作为展示名(与 base 行为一致, base 未返回用户信息)
                LoggedInUser user = new LoggedInUser(username, username);
                return new Result.Success<>(user);
            } else {
                // 失败: 用 AboxConstants.codeMap 把返回码映射成中文提示
                String code = abRet != null ? abRet.getCode() : "unknown";
                String msg = AboxConstants.codeMap.get(code);
                if (msg == null) {
                    msg = "登录失败: " + code;
                }
                return new Result.Error(new IOException(msg));
            }
        } catch (Exception e) {
            // 网络异常 / SDK 初始化异常等
            return new Result.Error(new IOException("登录异常: " + e.getMessage(), e));
        }
    }

    public void logout() {
        // TODO: revoke authentication
    }
}
