import 'dart:convert';

import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/qr/qr_parking_model.dart';
import 'package:diplomaticquarterapp/core/service/qr_service.dart';
import 'package:diplomaticquarterapp/core/viewModels/base_view_model.dart';

import '../../locator.dart';

class QrViewModel extends BaseViewModel {
  QrService _qrService = locator<QrService>();
  bool isSavePark = false;
  QRParkingModel qrParkingModel;

  readQr() async {
    //TODO fix the barcode scan
    String result = (await BarcodeScanner.scan())?.rawContent;
    var data = json.decode(result);
    var qRParkingID = data['QRParkingID'];
    setState(ViewState.BusyLocal);
    await _qrService.getQRParkingByID(qRParkingID);
    if (_qrService.hasError) {
      error = _qrService.error;
      setState(ViewState.ErrorLocal);
    } else {
      if (_qrService.qRParkingList.length > 0) {
        qrParkingModel = _qrService.qRParkingList[0];
        await sharedPref.setObject(IS_GO_TO_PARKING, qrParkingModel);
        isSavePark = true;
        setState(ViewState.Idle);
      } else {
        error = "Invalid Qr Code";
        setState(ViewState.ErrorLocal);
      }
    }
  }

  getIsSaveParking() async {
    setState(ViewState.Busy);
    var parking = await sharedPref.getObject(IS_GO_TO_PARKING);
    if (parking != null) {
      isSavePark = true;
      qrParkingModel = QRParkingModel.fromJson(parking);
    }
    setState(ViewState.Busy);
  }

  clearParking() async {
    setState(ViewState.Busy);
    await sharedPref.setObject(IS_GO_TO_PARKING, null);
    isSavePark = false;
    qrParkingModel = null;
    setState(ViewState.Idle);
  }
}
