import 'package:fis_jsonrpc/rpc.dart';
import 'package:vitalapp/rpc.dart';
import 'package:vitalapp/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;
  }

  @override
  Future<UserDTO?> getUserDetailAsync() async {
    try {
      return await rpc.user.getUserDetailAsync(
        GetUserRequest(
          token: Store.user.token,
          code: Store.user.userCode,
        ),
      );
    } catch (e) {
      return null;
    }
  }

  @override
  Future<bool> updateUserAsync(UserDTO dto) async {
    try {
      var request = UpdateUserRequest(
        token: Store.user.token,
        code: dto.code,
        realName: dto.realName,
        phone: dto.phone,
        headImageToken: dto.headImageToken,
      );
      var result = await rpc.user.updateUserAsync(request);
      if (result) {
        await Store.user.updateUserInfo(dto);
      }
      return result;
    } catch (e) {}
    return false;
  }

  @override
  Future<String> getUserPasswordDetailAsync() async {
    try {
      var result = await rpc.userPassword.getUserPasswordDetailAsync(
          GetUserPasswordRequest(
              token: Store.user.token, code: Store.user.userCode));
      return result.secretPassword ?? '';
    } catch (e) {}
    return '';
  }

  @override
  Future<bool> updateUserPasswordAsync(String secretPassword) async {
    try {
      var result = await rpc.userPassword.updateUserPasswordAsync(
          UpdateUserPasswordRequest(
              token: Store.user.token,
              code: Store.user.userCode,
              secretPassword: secretPassword));
      return result;
    } catch (e) {}
    return false;
  }
}
