import 'package:dart_json_mapper/dart_json_mapper.dart';
import 'package:get/get.dart';
import 'package:naiyouwl/app/common/constants.dart';
import 'package:naiyouwl/app/data/model/LoginMode.dart';

import '../../../common/LogHelper.dart';
import '../../../common/SharedPreferencesUtil.dart';
import '../../../data/model/LocalUser.dart';
import '../../../network/api_service.dart';
import '../../../routes/app_pages.dart';

class LoginController extends GetxController {

  final count = 0.obs;
  var isLoading = false.obs;
  var loginModes = LoginMode().obs;
  var localUsers = LocalUser().obs;
  var errorMsg = ''.obs;

  Future<void> fetchLogin(username,password) async {
    try {
      isLoading.value = true;
      loginModes.value = await ApiService().login(kLogin,data: {"email":username,"password":password});

      if(loginModes.value.accessToken != null){
        await SharedPreferencesUtil().setString("token", loginModes.value.accessToken.toString());
        var userModes = LocalUser(email: username,password: password,accessToken: loginModes.value.accessToken.toString());
        await SharedPreferencesUtil().setString("localUser", JsonMapper.serialize(userModes));
      }
      Get.offNamed(Routes.HOME,arguments: loginModes.value);

    } catch (e) {
      errorMsg.value = e.toString();
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> fetchLocalUser() async {
    try {
      String? data  = await SharedPreferencesUtil().getString("localUser");
      if(data  != null){
        localUsers.value = JsonMapper.deserialize<LocalUser>(data)!;
        LogHelper().d(localUsers.value.email);
      }
    } catch (e) {
      errorMsg.value = e.toString();
    } finally {
      isLoading.value = false;
    }
  }
  @override
  void onInit() {
    super.onInit();
    fetchLocalUser();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void increment() => count.value++;

  String username() => localUsers.value.email.toString();
  String password() => localUsers.value.password.toString();
  String accToken() => localUsers.value.accessToken.toString();
}
