import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/bloc/profile/eligibility/eligibility_bloc.dart';
import 'package:unit2/model/profile/work_history.dart';
import 'package:unit2/model/utils/agency.dart';
import 'package:unit2/model/utils/agency_position.dart';
import 'package:unit2/model/utils/position.dart';
import 'package:unit2/sevices/profile/work_history_services.dart';
import 'package:unit2/utils/profile_utilities.dart';

import '../../../model/utils/category.dart';

part 'workHistory_event.dart';
part 'workHistory_state.dart';

class WorkHistoryBloc extends Bloc<WorkHistorytEvent, WorkHistoryState> {
  List<WorkHistory> workExperiences = [];
  List<Position> agencyPositions = [];
  List<Agency> agencies = [];
  List<AppoinemtStatus> appointmentStatus = [];
  List<Category> agencyCategory = [];
  WorkHistoryBloc() : super(EducationInitial()) {
    ////GET WORK HISTORIES
    on<GetWorkHistories>((event, emit) async {
      emit(WorkHistoryLoadingState());
      try {
        if (workExperiences.isEmpty) {
          List<WorkHistory> works = await WorkHistoryService.instance
              .getWorkExperiences(event.profileId, event.token);
          workExperiences = works;
        }
        emit(WorkHistoryLoaded(workExperiences: workExperiences));
      } catch (e) {
        emit(WorkHistoryErrorState(message: e.toString()));
      }
    });
///// LOAD WORK HISTORIES
    on<LoadWorkHistories>((event, emit) {
      emit(WorkHistoryLoadingState());
      emit(WorkHistoryLoaded(workExperiences: workExperiences));
    });
    ////DELETE
    on<DeleteWorkHistory>((event, emit) async {
      try {
        final bool success = await WorkHistoryService.instance.delete(
            profileId: event.profileId,
            token: event.token,
            work: event.workHistory);
        if (success) {
          workExperiences.removeWhere(
              (WorkHistory element) => element.id == event.workHistory.id);
          emit(DeletedState(success: success));
        } else {
          emit(DeletedState(success: success));
        }
      } catch (e) {
        emit(WorkHistoryErrorState(message: e.toString()));
      }
    });
    //// ADD WORK HISTORIES
    on<AddWorkHostory>((event, emit) async {
      try {
        Map<dynamic, dynamic> status = await WorkHistoryService.instance.add(
            isPrivate: event.isPrivate,
            workHistory: event.workHistory,
            token: event.token,
            profileId: event.profileId);
        if (status['success']) {
          WorkHistory workHistory = WorkHistory.fromJson(status['data']);
          workExperiences.add(workHistory);
          emit(WorkHistoryAddedState(response: status));
        } else {
          emit(WorkHistoryAddedState(response: status));
        }
      } catch (e) {
        emit(WorkHistoryErrorState(message: e.toString()));
      }
    });

////UPDATE WORK HISTORY
    on<UpdateWorkHistory>((event, emit) async {
      try {
        Map<dynamic, dynamic> status = await WorkHistoryService.instance.update(
            oldWorkHistory: event.oldWorkHistory,
            newWorkHistory: event.workHistory,
            token: event.token,
            profileId: event.profileId);
        if (status['success']) {
          WorkHistory workHistory = WorkHistory.fromJson(status['data']);
          workExperiences.removeWhere((WorkHistory work) {
            return work.id == event.oldWorkHistory.id;
          });
          workExperiences.add(workHistory);
          emit(WorkHistoryEditedState(response: status));
        } else {
          emit(WorkHistoryEditedState(
            response: status,
          ));
        }
      } catch (e) {
        emit(WorkHistoryErrorState(message: e.toString()));
      }
    });

////SHOW EDIT WORK HISTORIES
    on<ShowEditWorkHistoryForm>((event, emit) async {
      try {
        /////POSITIONS------------------------------------------
        if (agencyPositions.isEmpty) {
          List<Position> positions =
              await WorkHistoryService.instance.getAgencyPosition();
          agencyPositions = positions;
        }

        /////AGENCIES------------------------------------------
        if (agencies.isEmpty) {
          List<Agency> newAgencies =
              await ProfileUtilities.instance.getAgecies();
          agencies = newAgencies;
        }

        /////Category Agency------------------------------------------
        if (agencyCategory.isEmpty) {
          List<Category> categoryAgencies =
              await ProfileUtilities.instance.agencyCategory();
          agencyCategory = categoryAgencies;
        }
        /////////-------------------------------------
        if (appointmentStatus.isEmpty) {
          List<AppoinemtStatus> status =
              WorkHistoryService.instance.getAppointmentStatusList();
          appointmentStatus = status;
        }

        emit(EditWorkHistoryState(
            workHistory: event.workHistory,
            agencyPositions: agencyPositions,
            appointmentStatus: appointmentStatus,
            agencyCategory: agencyCategory,
            agencies: agencies));
      } catch (e) {
        emit(WorkHistoryErrorState(message: e.toString()));
      }
    });
    ////SHOW ADD FORM WORK HISTORIES
    on<ShowAddWorkHistoryForm>((event, emit) async {
      emit(WorkHistoryLoadingState());
      try {
        /////POSITIONS------------------------------------------
        if (agencyPositions.isEmpty) {
          List<Position> positions =
              await WorkHistoryService.instance.getAgencyPosition();
          agencyPositions = positions;
        }

        /////AGENCIES------------------------------------------
        if (agencies.isEmpty) {
          List<Agency> newAgencies =
              await ProfileUtilities.instance.getAgecies();
          agencies = newAgencies;
        }

        /////Category Agency------------------------------------------
        if (agencyCategory.isEmpty) {
          List<Category> categoryAgencies =
              await ProfileUtilities.instance.agencyCategory();
          agencyCategory = categoryAgencies;
        }
        /////////-------------------------------------
        if (appointmentStatus.isEmpty) {
          List<AppoinemtStatus> status =
              WorkHistoryService.instance.getAppointmentStatusList();
          appointmentStatus = status;
        }

        emit(AddWorkHistoryState(
            agencyPositions: agencyPositions,
            appointmentStatus: appointmentStatus,
            agencyCategory: agencyCategory,
            agencies: agencies));
      } catch (e) {
        emit(WorkHistoryErrorState(message: e.toString()));
      }
    });
  }
}
