
import 'package:barcode_scan2/model/scan_result.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:unit2/model/roles/pass_check/passer_info.dart';
import 'package:unit2/sevices/roles/pass_check_services.dart';
import '../../../utils/scanner.dart';
part 'pass_check_event.dart';
part 'pass_check_state.dart';

class PassCheckBloc extends Bloc<PassCheckEvent, PassCheckState> {
  PassCheckBloc() : super(PassCheckInitial()) {
    int? roleId;
    String? uuid;
    bool? otherInputs;
    String? io;
    dynamic assignedArea;
    int? checkerId;
    String? token;
    int? stationId;
    String? cpId;
    on<GetPassCheckAreas>((event, emit) async {
      try {
        emit(PassCheckLoadingState());
        List<dynamic> response = await PassCheckServices.instance
            .getPassCheckArea(roleId: event.roleId, userId: event.userId);
        roleId = event.roleId;
        emit(AssignAreaLoaded(assignedArea: response, roleId: roleId!));
      } catch (e) {
        emit(PassCheckErrorState(message: e.toString()));
      }
    });
    on<SetScannerSettings>((event, emit) {
      otherInputs = event.includeOtherInputs;
      checkerId = event.checkerId;
      io = event.entranceExit;
      token = event.token;
      roleId = event.roleId;
      assignedArea = event.assignedArea;
      emit(SettingSaved(
          assignedArea: assignedArea,
          checker: checkerId!,
          io: io!,
          otherInputs: otherInputs!,
          roleId: roleId!,
          token: token!));
    });
    on<ScanError>((event, emit) {
      emit(SettingSaved(
          assignedArea: assignedArea,
          checker: checkerId!,
          io: io!,
          otherInputs: otherInputs!,
          roleId: roleId!,
          token: token!));
    });
    on<PerformIncomingPostLog>((event, emit) {
      add(PerformPostLogs(
          checkerId: checkerId!,
          cpId: cpId,
          destination: null,
          io: io!.toLowerCase() == "incoming" ? "i" : "o",
          otherInputs: otherInputs!,
          passerId: uuid!,
          roleId: roleId!,
          stationId: stationId,
          temp: event.temp));
    });

    on<PerformOutgoingPostLog>((event, emit) {
      add(PerformPostLogs(
          checkerId: checkerId!,
          cpId: cpId,
          destination: event.destination,
          io: io!.toLowerCase() == "incoming" ? "i" : "o",
          otherInputs: otherInputs!,
          passerId: uuid!,
          roleId: roleId!,
          stationId: stationId,
          temp: null));
    });
    on<ScanQr>((event, emit) async {
      ScanResult result = await QRCodeBarCodeScanner.instance.scanner();
      if (result.rawContent.toString().isNotEmpty) {
        uuid = result.rawContent.toString();
        emit(PassCheckLoadingState());
        try {
          PasserInfo? passerInfo = await PassCheckServices.instance
              .getPasserInfo(uuid: uuid!, token: event.token);
          if (roleId == 41 || roleId == 13 || roleId == 17 || roleId == 22) {
            stationId = assignedArea.id;
          } else if (roleId == 7) {
            cpId = assignedArea.brgycode;
          } else if (roleId == 10) {
            cpId = assignedArea.purokdesc;
          } else if (roleId == 16) {
            cpId = assignedArea.id;
          }
          if (passerInfo == null) {
            Fluttertoast.showToast(
                msg: "QR CODE IS INVALID",
                fontSize: 24,
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.CENTER,
                backgroundColor: Colors.black,
                textColor: Colors.white);
            emit(QRInvalid(token: token!));
          } else {
            if (otherInputs!) {
              if (io?.toLowerCase() == 'incoming') {
                emit(IncomingScanState());
              } else {
                emit(OutGoingScanState());
              }
            } else {
              add(PerformPostLogs(
                  checkerId: checkerId!,
                  cpId: cpId,
                  destination: null,
                  io: io!.toLowerCase() == "incoming" ? "i" : "o",
                  otherInputs: otherInputs!,
                  passerId: uuid!,
                  roleId: roleId!,
                  stationId: stationId,
                  temp: null));
            }
          }
        } catch (e) {
          emit(PassCheckErrorState(message: e.toString()));
        }
      } else {
        emit(SettingSaved(
            assignedArea: assignedArea,
            checker: checkerId!,
            io: io!,
            otherInputs: otherInputs!,
            roleId: roleId!,
            token: token!));
      }
    });
    on<PerformPostLogs>((event, emit) async {
      emit(PassCheckLoadingState());
      try {
        final bool success = await PassCheckServices.instance.performPostLogs(
            passerId: event.passerId,
            chekerId: event.checkerId,
            temp: event.temp,
            destination: event.destination,
            io: event.io,
            stationId: event.stationId,
            cpId: event.cpId,
            otherInputs: event.otherInputs,
            roleid: event.roleId);
        if (success) {
            Fluttertoast.showToast(
              msg: "SUCCESSFULLY SAVED",
              fontSize: 24,
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              backgroundColor: Colors.black,
              textColor: Colors.white);
          emit(ScanSuccess(token: token!));
        } else {
          Fluttertoast.showToast(
              msg: "SCAN FAILED",
              fontSize: 24,
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              backgroundColor: Colors.black,
              textColor: Colors.white);
          emit(ScanFailed(token: token!));
        }
      } catch (e) {
        emit(PassCheckErrorState(message: e.toString()));
      }
    });
  }
}
