import 'dart:convert';

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

class CaptainProfileController extends GetxController {
  bool isLoading = false;
  TextEditingController vin = TextEditingController();
  TextEditingController color = TextEditingController();
  TextEditingController make = TextEditingController();
  TextEditingController model = TextEditingController();
  TextEditingController year = TextEditingController();
  TextEditingController expirationDate = TextEditingController();

  Future updateFields() async {
    var res = await CRUD().post(link: AppLink.updateRegisrationCar, payload: {
      'driverID': box.read(BoxName.driverID),
      'vin': vin.text,
      'color': color.text,
      'model': model.text,
      'make': make.text,
      'year': year.text,
      'expirationDate': expirationDate.text,
    });

    if (jsonDecode(res)['status'] == 'success') {
      box.write(BoxName.vin, vin.text);
      box.write(BoxName.color, color.text);
      box.write(BoxName.model, model.text);
      box.write(BoxName.make, make.text);
      box.write(BoxName.year, year.text);
      box.write(BoxName.expirationDate, expirationDate.text);

      Get.back();
    }
  }

  Map captainProfileData = {};
  Future getProfileData() async {
    var res = await CRUD().get(
        link: AppLink.getCaptainProfile,
        payload: {'id': box.read(BoxName.driverID)});
    if (res != 'failure') {
      var d = jsonDecode(res);
      captainProfileData = d['message'];
      update();
      print(d['message']);
      box.write(BoxName.sexDriver, d['message']['gender']);
      box.write(BoxName.dobDriver, d['message']['birthdate']);
    }
  }

  @override
  void onInit() {
    if (box.read(BoxName.dobDriver).toString().isEmpty) {
      getProfileData();
    }

    super.onInit();
  }
}
