import { useAudioStore } from "_store/audioStore";
import {
	LocalTrackPublication,
	RemoteParticipant,
	RemoteTrack,
	RemoteTrackPublication,
} from "livekit-client";

const initialTrackTimeouts = new Map<string, NodeJS.Timeout>();

export const handleTrackSubscribed = (
	track: RemoteTrack,
	publication: RemoteTrackPublication,
	participant: RemoteParticipant,
) => {
	const element = track.attach();
	element.pause();

	if (!track.isMuted) {
		initialTrackTimeouts.set(
			participant.sid,
			setTimeout(() => {
				useAudioStore.getState().addSpeakingParticipant(participant);
			}, 1000),
		);
	}
	setTimeout(() => {
		element.play();
	}, 1000);

	track.on("unmuted", () => {
		useAudioStore.getState().addSpeakingParticipant(participant);
		element.volume = useAudioStore.getState().settings.radioVolume;
	});

	track.on("muted", () => {
		clearTimeout(initialTrackTimeouts.get(participant.sid));
		initialTrackTimeouts.get(participant.sid);
		useAudioStore.getState().removeSpeakingParticipant(participant);
	});
};

export const handleTrackUnsubscribed = (track: RemoteTrack) => {
	// remove tracks from all attached elements
	track.detach();
};

export const handleLocalTrackUnpublished = (publication: LocalTrackPublication) => {
	// when local tracks are ended, update UI to remove them from rendering
	publication.track?.detach();
};

export const handleDisconnect = () => {
	console.log("disconnected from room");
};
