import 'package:bloc/bloc.dart';

import 'package:e_commerce_training/res/R.dart';
import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/model/request/change_password_request.dart';
import 'package:e_commerce_training/src/util/logger.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:e_commerce_training/src/util/validator.dart';
import 'package:equatable/equatable.dart';

part 'change_pass_state.dart';

class ChangePassCubit extends Cubit<ChangePassState> with Validators {
  final AppRepository repository;
  bool isCheckPass = true;

  ChangePassCubit(this.repository) : super(ChangePassInitial());

  void validateCurrentPassword(String password) {
    emit(ChangePassInitial());
    String? error = checkPass(password);
    emit(ValidateCurrentPasswordError(error));
  }

  void validateNewPassword(String password) {
    emit(ChangePassInitial());
    String? error = checkPass(password);
    emit(ValidateNewPasswordError(error!));
  }

  void validateRePassword(String password) {
    emit(ChangePassInitial());
    String? error = checkPass(password);
    emit(ValidateRePasswordError(error!));
  }

  Future<void> changePass(String currentPassword, String newPassWord, String rePassWord) async {
    emit(ChangePassLoading());
    String password = currentPassword;
    String newPassword = newPassWord;
    String rePassword = rePassWord;
    String? errorCurrent = checkPass(password);
    String? errorNew = checkPass(newPassword);
    String? errorRe = checkRePass(newPassword, rePassword);
    if (!Util.isEmpty(errorCurrent!)) {
      emit(ChangePassFailure(errorCurrent));
      return;
    }
    if (!Util.isEmpty(errorNew!)) {
      emit(ChangePassFailure(errorNew));
      return;
    }
    if (!Util.isEmpty(errorRe!)) {
      emit(ChangePassFailure(errorRe));
      return;
    }
    ChangePasswordRequest request = ChangePasswordRequest(password: password, newPassword: newPassword);
    ChangePassState state = _handleChangePass(await repository.getListCity());
    emit(state);
  }

  ChangePassState _handleChangePass(Object data) {
    if (data is String) {
      return ChangePassFailure(data);
    } else {
      try {
//        CommonResponseEntity entity = CommonResponseEntity.fromJson(data);
//        return ChangePassSuccess(entity.message);
        return ChangePassSuccess(R.string.change_password_success);
      } catch (e) {
        logger.e(e.toString());
        return ChangePassFailure(R.string.error);
      }
    }
  }
}
