import 'package:get/get.dart';
import 'package:location/base/base_controller.dart';
import 'package:location/data/repositories/account_repository.dart';
import 'package:location/resource/string.gen.dart';
import 'package:location/utils/toast_util.dart';

import '../../data/bean/user_info.dart';
import '../../handler/error_handler.dart';

class UserAvatarController extends BaseController {
  final List<String> avatarList;

  UserAvatarController(this.avatarList);

  final AccountRepository accountRepository = AccountRepository.getInstance();

  final RxnString _selectedAvatar = RxnString();

  String? get selectedAvatar => _selectedAvatar.value;

  UserInfo? get mineInfo => accountRepository.mineUserInfo.value;

  void onSelectAvatarClick(String url) {
    _selectedAvatar.value = url;
  }

  void onSelectedClick() {
    final avatar =
        _selectedAvatar.value ?? accountRepository.mineUserInfo.value.avatar;
    if (avatar == null) {
      ToastUtil.show(StringName.accountPleaseSelectAvatar);
      return;
    }
    onAvatarSelected(avatar);
  }

  void onAvatarSelected(String avatar) {
    accountRepository.userAvatarUpdate(avatar).then((_) {
      ToastUtil.show(StringName.mineUpdateAvatarSuccess);
      Get.back();
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void onCloseClick() {
    Get.back();
  }
}
