import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:service/constant/api_key.dart';
import 'package:service/constant/box_name.dart';
import 'package:service/constant/links.dart';
import 'package:service/controller/functions/crud.dart';
import 'package:service/main.dart';

import '../views/home/main.dart';

class LoginController extends GetxController {
  var email = TextEditingController();
  var password = TextEditingController();
  final formKey = GlobalKey<FormState>();

  void login() async {
    if (box.read(BoxName.email) == AK.emailService) {
      Get.off(Main());
    } else {
      if (formKey.currentState!.validate()) {
        var res = await CRUD().get(link: AppLink.login, payload: {
          "email": email.text,
          "password": password.text,
        });
        if (res != 'failure') {
          var d = jsonDecode(res);
          if (d['message'] == "Login successful") {
            box.write(BoxName.email, email.text);

            Get.off(() => Main());
          }
        }
      }
    }
  }
}
