import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";

/**
 * Editor chunk saves and reloads share the same `EDITOR_CHUNK` reply.
 * After `EDITOR_SAVE_CHUNK` the local draft is still dirty (baseline is not
 * updated until the ack is applied). Treating that ack like a reconnect reload
 * leaves the Save button dirty even though the server already persisted.
 */

export function editorChunkSaveKey (dimensionId, chunkX, chunkY)
{
	return `${normalizeDimensionId(dimensionId ?? OVERWORLD_ID)}:${chunkX | 0},${chunkY | 0}`;
}

/** Identity of the chunk a local editor draft belongs to. */
export function editorDraftOwner (dimensionId, chunkX, chunkY)
{
	return {
		dimensionId: normalizeDimensionId(dimensionId ?? OVERWORLD_ID),
		chunkX: chunkX | 0,
		chunkY: chunkY | 0
	};
}

export function sameEditorChunk (a, b)
{
	if (!a || !b)
	{ return false; }
	return editorChunkSaveKey(a.dimensionId, a.chunkX, a.chunkY)
		=== editorChunkSaveKey(b.dimensionId, b.chunkX, b.chunkY);
}

/**
 * Chunk the pending local edits belong to — used for save, discard, and
 * sessionStorage backup. Never the chunk merely selected after navigation.
 */
export function editorDirtyChunk (draftOwner, viewed)
{
	return draftOwner ?? viewed;
}

/**
 * Whether an incoming selected-chunk `EDITOR_CHUNK` should replace the local draft.
 * Save acks must apply even while dirty. Non-ack reloads must not wipe unsaved paint
 * on the same chunk. A payload for a *different* chunk must not inherit leftover
 * dirty paint from the chunk that was just left.
 *
 * @param {{
 *   isSaveAck?: boolean,
 *   isDirty?: boolean,
 *   incoming?: { dimensionId?: string, chunkX?: number, chunkY?: number }|null,
 *   draftOwner?: { dimensionId?: string, chunkX?: number, chunkY?: number }|null
 * }} options
 */
export function shouldApplySelectedEditorChunk ({
	isSaveAck = false,
	isDirty = false,
	incoming = null,
	draftOwner = null
} = {})
{
	if (isSaveAck || !isDirty)
	{ return true; }
	if (incoming && draftOwner && !sameEditorChunk(incoming, draftOwner))
	{ return true; }
	return false;
}
