import { useDialogStore } from "@/contexts/dialog/lib/useDialogStore";
import { EventModel } from "@/contracts/client.schemas";
import { useAudioStore } from "@/features";

import { ASSET_CARD_DIALOG_KEY, AssetCardDialog } from "../AssetCardDialog";
import { useWatcherStore } from "../store/watcher.store";

export const useWatcher = () => {
	const watcherStore = useWatcherStore();
	const dialogs = useDialogStore();
	const audioStore = useAudioStore();

	const openEventCard = (assetId: string, playSound?: boolean) => {
		watcherStore.setCurrentAssetId(assetId);
		// TODO: remake to openning asset card
		const cardAlreadyOpened = dialogs.stack.some(
			(x) => x.key === ASSET_CARD_DIALOG_KEY,
		);
		if (!cardAlreadyOpened) {
			dialogs.push({
				key: ASSET_CARD_DIALOG_KEY,
				content: <AssetCardDialog />,
			});
		}

		if (playSound) {
			audioStore.setIsPlaying(true);
		}
	};

	const closeEventCard = () => {
		// TODO: move events to asset card
		// dialogs.close(Dialogs.EVENT_CARD);
	};

	const selectAsset = (assetId: string) => {
		watcherStore.setCurrentAssetId(assetId);
	};

	const alarmedAssets = watcherStore.assets.filter((x) =>
		watcherStore.commonAlarms.some((y) => y.event.assetId === x.id),
	);

	const subscribeToOnEvent = (callback: (event: EventModel) => void) => {
		watcherStore.addEventHandler(callback);
	};
	const unsubscribeFromOnEvent = (callback: (event: EventModel) => void) => {
		watcherStore.removeEventHandler(callback);
	};

	return {
		openEventCard,
		closeEventCard,
		selectAsset,
		alarmedAssets,
		subscribeToOnEvent,
		unsubscribeFromOnEvent,
	};
};
