

import 'package:get/get.dart';
import 'package:mighty_school/api_handle/api_checker.dart';
import 'package:mighty_school/common/widget/custom_snackbar.dart';
import 'package:mighty_school/feature/authentication/domain/authentication_repository.dart';
import 'package:mighty_school/feature/parent_module/parent_profile/logic/parent_profile_controller.dart';
import 'package:mighty_school/feature/profile/logic/profile_controller.dart';
import 'package:mighty_school/feature/sidebar/controller/side_menu_bar_controller.dart';
import 'package:mighty_school/helper/route_helper.dart';
import 'package:mighty_school/util/app_constants.dart';

class AuthenticationController extends GetxController implements GetxService{
  final AuthenticationRepository authenticationRepository;
  AuthenticationController({required this.authenticationRepository});


  bool isLoading = false;
  Future<void> login( String email, String password) async {
    isLoading = true;
    update();
    Response? response = await authenticationRepository.login(email: email, password: password);
    if(response!.statusCode == 200){
      isLoading = false;
      setUserToken(response.body['data']['access_token']);
      if(response.body['data']['role'] == AppConstants.parent){
        Get.find<ParentProfileController>().getProfileInfo().then((val){
          if(val.statusCode == 200){
            Get.offAllNamed(RouteHelper.getDashboardRoute());
            Get.find<SideMenuBarController>().toggleSideMenu(true);
            Get.find<SideMenuBarController>().updateParentSideMenuItems();
          }
        });
      }else {
        Get.find<ProfileController>().getProfileInfo().then((val){
        if(val.statusCode == 200){
          Get.offAllNamed(RouteHelper.getDashboardRoute());
          Get.find<SideMenuBarController>().toggleSideMenu(true);
        }
      });
      }
    }else if(response.statusCode == 1){
      isLoading = false;
      showCustomSnackBar("CORS ERROR");
    }else{
      isLoading = false;
      ApiChecker.checkApi(response);
    }
    update();

  }

  Future <void> setUserToken(String token) async{
    authenticationRepository.saveUserToken(token);
  }

  Future <void> setUserType(String type) async{
    authenticationRepository.setUSerTypeParent(type);
  }

  String getUserType() {
    return authenticationRepository.getUserType();
  }

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

  String getToken() {
    return authenticationRepository.getUserToken();
  }

  bool isActiveRememberMe = false;
  void toggleRememberMe() {
    isActiveRememberMe = !isActiveRememberMe;
    update();
  }

  int selectedIndex = 0;
  void setSelectedIndex(int index) {
    selectedIndex = index;
    update();
  }

  void saveEmailAndPassword(String number, String password) {
    authenticationRepository.saveEmailAndPassword(number, password);
  }
  Future <bool> clearSharedData() async {
    return authenticationRepository.clearSharedData();
  }

}