import 'package:fis_jsonrpc/rpc.dart';
import 'package:vnoteapp/rpc.dart';
import 'package:vnoteapp/store/store.dart';
import 'package:fis_common/helpers/encrypt.dart';
import 'package:fis_common/logger/logger.dart';

import 'interfaces/account.dart';

class AccountManager implements IAccountManager {
  @override
  Future<bool> login(String account, String password) async {
    try {
      final result = await rpc.login.commonLoginAsync(
        CommonLoginRequest(
          anyAccount: account,
          password:
              password.isEmpty ? '' : FEncryptHelper.symmetryEncrypt(password),
          platform: Platform.Android,
          loginSource: LoginSource.Android,
        ),
      );
      await Store.user.handleLogin(account, result.token!);
      return true;
    } catch (e) {
      return false;
    }
  }

  @override
  Future<bool> logout() async {
    try {
      await rpc.login.loginOutAsync(
        TokenRequest(token: Store.user.token),
      );
    } catch (e) {
      logger.e("AccountManager call logout error", e);
    }
    await Store.user.handleLogOut();
    return true;
  }
}
