import 'package:flutter/foundation.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:voice_buddies/app/widget/base_controller.dart';

import '../../../models/login_model.dart';
import '../../../utils/all_imports.dart';

class LoginController extends BaseController {
  TextEditingController email = TextEditingController(text: kDebugMode ? "bhumit.kmphitech@gmail.com" : "");
  TextEditingController passwordController = TextEditingController(text: kDebugMode ? "Bhumit@123" : "");

  String buildNumber = "";
  String version = "";

  Future<void> getCurrentVersionCode() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    buildNumber = packageInfo.buildNumber;
    version = packageInfo.version;
    update();
  }

  /// Login Api
  loginApi() async {
    FormData formData = FormData.fromMap({
      "email": email.text,
      "password": utils.generateMd5(passwordController.text),
    });

    final data = await APIFunction().apiCall(
      apiName: Constants.login,
      params: formData,
    );

    LoginDataModel model = LoginDataModel.fromJson(data);

    if (model.responseCode == 1) {
      await getStorageData.saveObject(getStorageData.loginData, model.data!);
      Get.offAllNamed(Routes.BOTTOM_BAR);
      passwordController.clear();
      email.clear();
    } else {
      utils.showSnackBar(message: model.responseMsg!, statusCode: model.responseCode);
    }
  }

  /// validation
  bool isValidation() {
    if (utils.isValidationEmpty(email.text.trim())) {
      utils.showSnackBar(message: AppStrings.errorMessageEmail);
      return false;
    } /*else if (!utils.emailValidator(email.text.trim())) {
      utils.showSnackBar(message: AppStrings.errorMessageValidEmail);
      return false;
    }*/
    else if (utils.isValidationEmpty(passwordController.text.trim())) {
      utils.showSnackBar(message: AppStrings.errorMessagePassword);
      return false;
    } else if (!utils.passwordValidator(passwordController.text.trim())) {
      utils.showSnackBar(message: AppStrings.errorMessageValidPassword);
      return false;
    }
    return true;
  }

  @override
  void onInit() {
    getCurrentVersionCode();
    super.onInit();
  }
}
