import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:service/helpers/helper.dart';
import 'package:service/helpers/snackbar.dart';

class LoginController extends GetxController {
  var isEnglishSelected = true.obs;

  final usernameController = TextEditingController();
  final passwordController = TextEditingController();

  @override
  void onClose() {
    usernameController.dispose();
    passwordController.dispose();
    super.onClose();
  }

  void toggleLanguage(bool isEnglish) {
    isEnglishSelected.value = isEnglish;
    Get.updateLocale(
        isEnglish ? const Locale('en', 'US') : const Locale('zh', 'CN'));
  }

  void doLogin() async {
    final username = usernameController.text.trim();
    final password = passwordController.text.trim();
    final res = await Helper().doLogin(username, password);
    if (res['code'] == 1) {
      if (res['message'] == 'Success') {
        Helper().writeData('userId', res['userId']);
        Helper().writeData('username', res['username']);
        Helper().writeData('regionId', res['regionId']);
        Helper().writeData('create', res['create']);
        Helper().writeData('read', res['read']);
        Helper().writeData('update', res['update']);
        Helper().writeData('delete', res['delete']);
        Get.offAndToNamed('/mainmenu');
      } else if (res['message'] == 'Success, but wrong credential') {
        CustomSnackbar().showErrorDialog('wrongPassword'.tr);
      }
    } else {
      CustomSnackbar().showErrorDialog('pleaseTryAgain'.tr);
    }
  }
}
