import type { BuildingType, Cost, Resource, Resources, UnitType, VillageState, VillageUpdated } from '~/types/game' const RESOURCES: Resource[] = ['wood', 'clay', 'iron', 'food'] /** * One village: the last server snapshot, resources projected to now, and the intents. * Call it from a page's setup(), since it listens for pushes while that page is mounted. */ export function useVillage(villageId: number) { const village = ref(null) const error = ref(null) const busy = ref(false) const errorText = useErrorText() const clock = useNow() // Server time minus client time, so projections use the server's clock. const offset = ref(0) const now = computed(() => clock.value + offset.value) async function run(event: string, data: object = {}) { busy.value = true error.value = null try { const state = await ws.send(event, { village_id: villageId, ...data }) offset.value = Date.parse(state.server_time) - Date.now() village.value = state } catch (e) { error.value = errorText(e) } finally { busy.value = false } } const refresh = () => run('village.show') /** stored + rate × elapsed, kept between 0 and the storage cap. */ const resources = computed(() => { const v = village.value if (!v) return null const hours = (now.value - Date.parse(v.resources_at)) / 3_600_000 const project = (r: Resource) => Math.min(v.storage_cap, Math.max(0, v.resources[r] + v.rates[r] * hours)) return Object.fromEntries(RESOURCES.map((r) => [r, project(r)])) as Resources }) const canAfford = (cost: Cost) => !!resources.value && resources.value.wood >= cost.wood && resources.value.clay >= cost.clay && resources.value.iron >= cost.iron /** Whole seconds until a server timestamp, never below zero. */ const secondsUntil = (iso: string) => Math.max(0, Math.ceil((Date.parse(iso) - now.value) / 1000)) // Refetch once when the next build order or the next unit in training is due, so // new buildings and trained troops show up without waiting for a push. const nextDue = computed(() => { const v = village.value if (!v) return null const times = [ ...v.queue.flatMap((o) => (o.finishes_at ? [Date.parse(o.finishes_at)] : [])), ...[v.levy.until, v.starvation.food_empty_at, v.starvation.desertion_at].flatMap((at) => (at ? [Date.parse(at)] : [])), ...v.military.flatMap((m) => m.queue.filter((o) => o.done < o.count).map((o) => Date.parse(o.starts_at) + (o.done + 1) * o.seconds_per_unit * 1000), ), ] return times.length ? Math.min(...times) : null }) watch( () => nextDue.value !== null && now.value >= nextDue.value, (due) => { if (due) refresh() }, ) ws.listenWhileMounted('village:updated', null, (data) => { if (data.village_id === villageId) refresh() }) return { village, resources, error, busy, canAfford, secondsUntil, refresh, build: (type: BuildingType) => run('village.build', { type }), upgrade: (buildingId: number) => run('village.upgrade', { building_id: buildingId }), demolish: (buildingId: number) => run('village.demolish', { building_id: buildingId }), cancel: (orderId: number) => run('village.cancel', { order_id: orderId }), setPriority: (buildingId: number, priority: number) => run('village.staff', { building_id: buildingId, priority }), /** One order per unit type, sent one after another; stops at the first refusal. */ recruit: async (buildingId: number, orders: { unit: UnitType; count: number }[]) => { for (const o of orders) { await run('village.recruit', { building_id: buildingId, unit: o.unit, count: o.count }) if (error.value) return false } return true }, cancelRecruit: (orderId: number) => run('village.cancelRecruit', { order_id: orderId }), levy: (count: number) => run('village.levy', { count }), endLevy: () => run('village.endLevy'), } }