enum DoorState { closed, opening, open, closing }

class Door {
  final int x;
  final int y;
  final int mapId;

  DoorState state = DoorState.closed;
  double offset = 0.0;
  int openTime = 0;
  static const int openDurationMs = 3000;

  Door({
    required this.x,
    required this.y,
    required this.mapId,
  });

  /// Updates animation. Returns the NEW state if it changed this frame, else null.
  DoorState? update(int currentTimeMs) {
    if (state == DoorState.opening) {
      offset += 0.02;
      if (offset >= 1.0) {
        offset = 1.0;
        state = DoorState.open;
        openTime = currentTimeMs;
        return DoorState.open;
      }
    } else if (state == DoorState.open) {
      if (currentTimeMs - openTime > openDurationMs) {
        state = DoorState.closing;
        return DoorState.closing;
      }
    } else if (state == DoorState.closing) {
      offset -= 0.02;
      if (offset <= 0.0) {
        offset = 0.0;
        state = DoorState.closed;
        return DoorState.closed;
      }
    }
    return null;
  }

  /// Triggers the opening process. Returns true if it successfully started opening.
  bool interact() {
    if (state == DoorState.closed || state == DoorState.closing) {
      state = DoorState.opening;
      return true;
    }
    return false;
  }
}
