Untitled

mail@pastecode.io avatar
unknown
plain_text
10 days ago
7.5 kB
1
Indexable
Never
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:paywell_apps/data/dataSource/repository/api_response.dart';
import 'package:paywell_apps/models/licence/ess_licence_model.dart';
import 'package:paywell_apps/models/login/get_login/get_login_data_model.dart';
import 'package:paywell_apps/models/login/get_login/get_login_model.dart';
import 'package:paywell_apps/models/login/get_login/login_data_model.dart';
import 'package:paywell_apps/models/login/get_login/validate_login_model.dart';
import 'package:paywell_apps/models/response/base/response_model.dart';
import 'package:paywell_apps/utils/app_prefrence.dart';
import 'package:paywell_apps/utils/app_routes.dart';
import 'package:paywell_apps/widgets/common_widgets/toast.dart';

import '../data/repository/auth_repo.dart';

class AuthProvider with ChangeNotifier {
  final AuthRepo authRepo;

  AuthProvider({required this.authRepo});

  bool _isLoading = false;

  bool get isLoading => _isLoading;

  // Variables
  bool _passwordVisible = false;
  bool get passwordVisible => _passwordVisible;

  bool _isClickable = true;

  final _formKey = GlobalKey<FormState>();

  GlobalKey<FormState> get formKey => _formKey;

  ///Input controller
  TextEditingController clientCodeController = TextEditingController();
  TextEditingController usernameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  GetLoginModel? _loginModel;

  //Functions
  Future<void> onTapLogin(context) async {
    if (_isClickable) {
      if (_formKey.currentState?.validate() ?? false) {
        _isClickable = false;
        await login(clientCodeController.text, context);
      }
    }
  }

  void onTextObscure() {
    _passwordVisible = !_passwordVisible;
    notifyListeners();
  }

  Future<ResponseModel> login(clientCode, context) async {
    ResponseModel responseModel;
    _isLoading = true;
    notifyListeners();
    try {
      ApiResponse apiRegisterResponse = await authRepo.login(clientCode);

      if (apiRegisterResponse.response != null &&
          apiRegisterResponse.response!.statusCode == 200) {
        if (apiRegisterResponse.response?.data["status"]
            .toString()
            .contains("Success") ??
            false) {
          // Parse json data in Model class
          _loginModel =
              GetLoginModel.fromJson(apiRegisterResponse.response?.data);
          await authRepo.setUserToken(_loginModel?.token ?? "");
          var d = json.decode(_loginModel?.result ?? "");
          var connectionString =
          ConnectionString.fromJson(d["ConnectionString"][0]);
          await authRepo.setValue(
              AppLocal.customerId, connectionString.customerid ?? "");
          await authRepo.setValue(
              AppLocal.clientCode, clientCodeController.text);

          // Validate Login
          var validateLoginModel = (await validateLogin());
          var licenseResp = await essLicenseFun(context);
          if (!licenseResp.isSuccess) {
            throw Error.safeToString(licenseResp.message);
          }
          if (validateLoginModel.isSuccess) {
            var res = jsonDecode(validateLoginModel.data.data ?? "");
            Login? login;
            if (res["Login"] == null) {
              throw Error.safeToString(validateLoginModel.data.message ?? "");
            }
            login = Login.fromJson(res["Login"][0]);
            await authRepo.setValue(AppLocal.companyCode, login.companyCode);
            await authRepo.setValue(AppLocal.empCode, login.empCode);
            await authRepo.setValue(AppLocal.userId, login.userId);
            await authRepo.setValue(AppLocal.applicableForEPunch, login.applicableForEPunch);
            if (login.mobileAppAllowed == 1) {
              FToast().toast(context, validateLoginModel.data.message);
              Navigator.pushNamedAndRemoveUntil(
                  context, AppRoute.leaveApplication, (route) => false);
              responseModel =
                  ResponseModel(true, 'Login Successful', _loginModel);
            } else {
              throw Error.safeToString("you are not eligible for mobile app");
            }
          } else {
            throw Error.safeToString(validateLoginModel.message);
          }
        } else {
          responseModel = ResponseModel(false, 'Login failed', null);
        }
      } else {
        responseModel =
            ResponseModel(false, apiRegisterResponse.error ?? "", null);
      }
    } catch (e) {
      FToast().toast(
          context, e.toString().replaceAll('\\""', "").replaceAll('"\\"', ""));
      responseModel = ResponseModel(false, 'Login Failed', null);
    }
    _isLoading = false;
    _isClickable = true;
    notifyListeners();
    return responseModel;
  }

  Future<ResponseModel> validateLogin() async {
    ResponseModel responseModel;
    notifyListeners();
    try {
      ApiResponse apiRegisterResponse = await authRepo.validateLogin({
        "username": usernameController.text,
        "password": passwordController.text,
      });

      if (apiRegisterResponse.response!.statusCode == 200) {
        if (apiRegisterResponse.response?.data["status"] == "Success") {
          responseModel = ResponseModel(
              true,
              'Validate Successful',
              ValidateLoginModel.fromJson(
                  apiRegisterResponse.response?.data ?? {}));
        } else {
          throw Error.safeToString("Validation Failed");
        }
      } else {
        throw Error.safeToString("Validation Failed");
      }
    } catch (e) {
      responseModel = ResponseModel(false, 'Validation Failed', null);
    }
    notifyListeners();
    return responseModel;
  }

  Future<ResponseModel> essLicenseFun(context) async {
    ResponseModel responseModel;
    notifyListeners();
    try {
      ApiResponse apiRegisterResponse = await authRepo.essLicenseFun({
        "username": usernameController.text,
        "password": passwordController.text,
      });

      if (apiRegisterResponse.response!.statusCode == 200) {
        if (apiRegisterResponse.response?.data["statusCode"] == "1") {
          responseModel = ResponseModel(true, '',
              EssLicenseModel.fromJson(apiRegisterResponse.response?.data));
        } else {
          throw Error.safeToString(
              apiRegisterResponse.response?.data['message']);
        }
      } else {
        throw Error.safeToString("License Failed");
      }
    } catch (e) {
      print("Error -> $e");
      responseModel = ResponseModel(false, e.toString().trim(), null);
    }
    notifyListeners();
    return responseModel;
  }

  Future<ResponseModel> logout() async {
    ResponseModel responseModel;
    _isLoading = true;
    try {
      responseModel = ResponseModel(true, "Logout", null);
      await clearSharedData();
    } on Exception {
      responseModel = ResponseModel(false, "Logout", null);
    }

    _isLoading = false;
    notifyListeners();
    return responseModel;
  }

  bool isLoggedIn() {
    return authRepo.isLoggedIn();
  }

  Future<bool> clearSharedData() async {
    return await authRepo.clearSharedData();
  }

  String getUserToken() {
    return authRepo.getUserToken();
  }

  void clear() {
    // Clear Provider
    notifyListeners();
  }
}
Leave a Comment