import 'package:flutter/material.dart';
import 'package:qadirneyriz/services/auth/auth.dart';
import 'package:qadirneyriz/setting/setting.dart';
import 'package:qadirneyriz/utils/enums/status.dart';

class AuthState extends ChangeNotifier {
  /// set and fetch language
  String language = setting.userLocalDb.getUser().language;
  Future<void> setLocale(String newLanguage) async {
    language = newLanguage;

    await setting.userLocalDb.saveUserField('language', newLanguage);
    notifyListeners();
  }

  // auth seviceses class
  AuthServices authServises = AuthServices();
  // login funtinulity

  Status statusLogin = Status.empty;
  String? messageLogin;
  Map? errorsLogin;

  Future<Status> login(
      {required String mobile, String? password, String? otp}) async {
    assert(password != null || otp != null);
    statusLogin = Status.loading;
    notifyListeners();
    try {
      final result = await authServises.loginApi(
          mobile: mobile, password: password, otp: otp);
      if (result == null) {
        statusLogin = Status.error;
      } else {
        if (result.isOk) {
          statusLogin = Status.ready;
          messageLogin = result.message;
        } else if (result.isOk == false) {
          errorsLogin = result.errors;
          messageLogin = result.message;
          statusLogin = Status.error;
        } else {
          statusLogin = Status.error;
        }
        notifyListeners();
      }
      notifyListeners();
    } catch (e) {
      statusLogin = Status.error;
    }
    notifyListeners();

    return statusLogin;
  }

  Status statusSendotp = Status.empty;
  String? messageSendOtp;
  Map? errorsSendOtp;
  Future<Status> sendOtp({
    required String mobile,
  }) async {
    statusSendotp = Status.loading;
    notifyListeners();
    try {
      final result = await authServises.sendOtpApi(mobile: mobile);
      if (result == null) {
        statusSendotp = Status.error;
      } else {
        // print(result);
        if (result.isOk) {
          statusSendotp = Status.ready;
          messageSendOtp = result.message;
        } else if (result.isOk == false) {
          errorsSendOtp = result.errors;
          messageSendOtp = result.message;
          statusSendotp = Status.error;
        } else {
          statusSendotp = Status.error;
        }
        notifyListeners();
      }
      notifyListeners();
    } catch (e) {
      statusSendotp = Status.error;
      // print(e);
    }
    notifyListeners();
    // print(statusSendotp);
    return statusSendotp;
  }


}
