import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:SEFER/constant/box_name.dart';
import 'package:SEFER/constant/links.dart';
import 'package:SEFER/controller/functions/crud.dart';
import 'package:SEFER/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 payload = {
      'driverID': box.read(BoxName.driverID),
    };

    if (vin.text.isNotEmpty) {
      payload['vin'] = vin.text;
    }

    if (color.text.isNotEmpty) {
      payload['color'] = color.text;
    }

    if (model.text.isNotEmpty) {
      payload['model'] = model.text;
    }

    if (make.text.isNotEmpty) {
      payload['make'] = make.text;
    }

    if (year.text.isNotEmpty) {
      payload['year'] = year.text;
    }

    if (expirationDate.text.isNotEmpty) {
      payload['expiration_date'] = expirationDate.text;
    }

    var res =
        await CRUD().post(link: AppLink.updateRegisrationCar, payload: payload);

    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);
      update();
      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']);
      box.write(BoxName.vin, d['message']['vin']);
      box.write(BoxName.color, d['message']['color']);
      box.write(BoxName.model, d['message']['model']);
      box.write(BoxName.carPlate, d['message']['car_plate']);
      box.write(BoxName.make, d['message']['make']);
      box.write(BoxName.year, d['message']['year']);
      box.write(BoxName.expirationDate, d['message']['expiration_date']);
      // box.write(BoxName.acc, d['message']['accountBank']);

      update();
    }
  }

  @override
  void onInit() {
    // if (box.read(BoxName.dobDriver) == null) {
    getProfileData();
    // }

    super.onInit();
  }
}
