import { schema, table, t } from "spacetimedb/server";

const spacetimedb = schema({
	videoState: table(
		{ public: true },
		{
			id: t.u64().primaryKey(),
			url: t.string(),
			subtitleUrl: t.string(),
			timePosition: t.f64(),
			isPlaying: t.bool(),
			lastUpdatedAt: t.timestamp(),
		},
	),
});
export default spacetimedb;

export const init = spacetimedb.init((ctx) => {
	// Insert initial video state row on first deploy
	ctx.db.videoState.insert({
		id: 1n,
		url: "https://cdn.cazzzer.com/LycoReco08.mkv",
		subtitleUrl: "",
		timePosition: 0.0,
		isPlaying: false,
		lastUpdatedAt: ctx.timestamp,
	});
});

export const onConnect = spacetimedb.clientConnected((_ctx) => {});
export const onDisconnect = spacetimedb.clientDisconnected((_ctx) => {});

export const set_url = spacetimedb.reducer({ url: t.string() }, (ctx, { url }) => {
	const row = ctx.db.videoState.id.find(1n);
	if (!row) return;
	ctx.db.videoState.id.update({
		...row,
		url,
		subtitleUrl: "", // Clear subtitle on new video
		timePosition: 0.0,
		isPlaying: false,
		lastUpdatedAt: ctx.timestamp,
	});
});

export const play = spacetimedb.reducer({ time_position: t.f64() }, (ctx, { time_position }) => {
	const row = ctx.db.videoState.id.find(1n);
	if (!row) return;
	ctx.db.videoState.id.update({
		...row,
		timePosition: time_position,
		isPlaying: true,
		lastUpdatedAt: ctx.timestamp,
	});
});

export const pause = spacetimedb.reducer({ time_position: t.f64() }, (ctx, { time_position }) => {
	const row = ctx.db.videoState.id.find(1n);
	if (!row) return;
	ctx.db.videoState.id.update({
		...row,
		timePosition: time_position,
		isPlaying: false,
		lastUpdatedAt: ctx.timestamp,
	});
});

export const seek = spacetimedb.reducer({ time_position: t.f64() }, (ctx, { time_position }) => {
	const row = ctx.db.videoState.id.find(1n);
	if (!row) return;
	ctx.db.videoState.id.update({
		...row,
		timePosition: time_position,
		lastUpdatedAt: ctx.timestamp,
	});
});

export const set_subtitle_url = spacetimedb.reducer({ url: t.string() }, (ctx, { url }) => {
	const row = ctx.db.videoState.id.find(1n);
	if (!row) return;
	ctx.db.videoState.id.update({
		...row,
		subtitleUrl: url,
		lastUpdatedAt: ctx.timestamp,
	});
});
