import 'package:krow/core/data/models/event/business_member_model.dart';
import 'package:krow/core/data/models/event/full_address_model.dart';
import 'package:krow/core/data/models/shift/shift_model.dart';
import 'package:krow/core/entity/event_entity.dart';
import 'package:krow/core/entity/position_entity.dart';

class ShiftEntity {
  final String id;
  final FullAddress? fullAddress;
  final List<BusinessMemberModel> managers;
  final List<PositionEntity> positions;
  EventEntity? parentEvent;

  final ShiftModel? dto;

  ShiftEntity({
    required this.id,
    this.fullAddress,
    this.managers = const [],
    this.positions = const [],
    this.dto,
  });

  ShiftEntity copyWith({String? id,
    FullAddress? fullAddress,
    List<BusinessMemberModel>? managers,
    List<PositionEntity>? positions,
    ShiftModel? dto}) {
    var newEntity = ShiftEntity(
      id: id ?? this.id,
      fullAddress: fullAddress ?? this.fullAddress,
      managers: managers ?? this.managers,
      positions: positions ?? this.positions,
      dto: dto ?? this.dto,
    );
    newEntity.parentEvent = parentEvent;
    int index =
        parentEvent?.shifts?.indexWhere((item) => item.id == this.id) ?? -1;
    if (index != -1) {
      parentEvent?.shifts?[index] = newEntity;
    }
    return newEntity;
  }

  static fromDto(ShiftModel model, DateTime date) {
    var entity = ShiftEntity(
      id: model.id,
      fullAddress: model.fullAddress,
      managers: model.contacts ?? [],
      positions: model.positions
          ?.map<PositionEntity>((e) => PositionEntity.fromDto(e, date))
          .toList() ??
          [],
      dto: model,
    );

    for (var element in entity.positions) {
      element.parentShift = entity;
      for (var contact in element.staffContacts) {
        contact.parentPosition = element;
      }
    }
    return entity;
  }

  static empty() {
    var entity = ShiftEntity(
        id: DateTime
            .now()
            .millisecondsSinceEpoch
            .toString(),
        positions: [
          PositionEntity.empty(),
        ]);

    for (var element in entity.positions) {
      element.parentShift = entity;
    }
    return entity;
  }

  @override
  int get hashCode =>
      id.hashCode ^ fullAddress.hashCode ^ managers.hashCode ^ positions
          .hashCode ^ (dto?.hashCode ?? 0);

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;

    if (other is! ShiftEntity) return false;

    return other.id == id &&
        other.fullAddress == fullAddress &&
        other.managers == managers &&
        other.positions == positions &&
        other.dto == dto;
  }
}
