import 'dart:async';
import 'package:absenkuv3/Repository/Model/mAbsensi.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Model/mIzin.dart';
import 'package:absenkuv3/Repository/Service/absensiApi.dart';
import 'package:absenkuv3/Repository/Service/serviceInfo.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

abstract class DataDetailAbsensiEvent {
  BuildContext? context;
  GlobalKey<ScaffoldState>? scaffoldKey;
}

class getDataDetailAbsensiEvent extends DataDetailAbsensiEvent {
  ModelFilter? modelFilter;
  String? idKaryawan;
  String? tglAbsen;
  getDataDetailAbsensiEvent(
    BuildContext _context,
    this.modelFilter,
    this.idKaryawan,
    this.tglAbsen,
  ) {
    context = _context;
  }
}

abstract class DataDetailAbsensiState {
  List<DataRekapAbsensi>? data;
  DataIzin? dataDetail;
}

class getDataDetailAbsensiSuccessState extends DataDetailAbsensiState {
  getDataDetailAbsensiSuccessState(
      DataDetailAbsensiEvent _event, List<DataRekapAbsensi>? _data) {
    data = _data;
  }
}

class DataDetailAbsensiProgressState extends DataDetailAbsensiState {}

class DataDetailAbsensiErrorState extends DataDetailAbsensiState {}

class DataDetailAbsensiBloc
    extends Bloc<DataDetailAbsensiEvent, DataDetailAbsensiState> {
  final dateFormat = new DateFormat('yyyy-MM');
  ModelFilter? modelFilter;
  DataDetailAbsensiState? initialState;
  List<DataRekapAbsensi>? listAbsensi;
  int offset = 0;
  int limit = ServerInfo.limit;

  DataDetailAbsensiBloc(DataDetailAbsensiState initialState)
      : super(initialState);

  @override
  Stream<DataDetailAbsensiState> mapEventToState(
      DataDetailAbsensiEvent event) async* {
    if (event is getDataDetailAbsensiEvent) {
      offset = 0;
      modelFilter = event.modelFilter;
      yield DataDetailAbsensiProgressState();
      RekapAbsensiRespon absensiRespon = await AbsensiApi()
          .getDataDetailAbsensi(
              modelFilter, offset, event.idKaryawan!, event.tglAbsen!);
      if (absensiRespon.success!) {
        listAbsensi = absensiRespon.data;
        yield getDataDetailAbsensiSuccessState(event, listAbsensi);
      } else
        yield DataDetailAbsensiErrorState();
    }
  }
}
