import React from "react";
import { MatrixApiEvent } from "../../api/matrix/MatrixApiEvent";
import type { UsersMap } from "../../api/matrix/MatrixApiProfile";
import type { Room } from "../../api/matrix/MatrixApiRoom";
import { RoomEventsManager } from "../../utils/RoomEventsManager";
import { AsyncWidget } from "../AsyncWidget";

export function RoomWidget(p: {
  room: Room;
  users: UsersMap;
}): React.ReactElement {
  const [roomMgr, setRoomMgr] = React.useState<undefined | RoomEventsManager>();

  const load = async () => {
    setRoomMgr(undefined);
    const messages = await MatrixApiEvent.GetRoomEvents(p.room);
    const mgr = new RoomEventsManager(p.room, messages);
    setRoomMgr(mgr);
  };

  return (
    <AsyncWidget
      loadKey={p.room.id}
      ready={!!roomMgr}
      load={load}
      errMsg="Failed to load room!"
      build={() => <>room</>}
    />
  );
}
