'use strict'; /* POST /towns/:id/withdraw. Reinforcements standing in host POP :id go home. Either side may do it: the host owner * sends them away, the units' owner calls them back. `units` defaults to the whole group. They travel home as a * return movement and stop drawing the host's power right away. */ const { GameError } = require('../errors'); const { settle } = require('../state'); const ctxOf = require('../military/ctx'); const U = require('../military/units'); const M = require('../military/movements'); const P = require('../military/power'); module.exports = function withdrawStationed(ctx0, { userId, hostTownId, ownerTownId, units }) { const ctx = ctxOf(ctx0); const { db, now } = ctx; const host = db.get('SELECT * FROM towns WHERE id = ?', hostTownId); const owner = db.get('SELECT * FROM towns WHERE id = ?', ownerTownId); if (!host || !owner) throw new GameError('not_found', { what: 'town' }); const mine = (t) => !!db.get('SELECT 1 AS x FROM operators WHERE id = ? AND user_id = ?', t.owner_id, userId); if (!mine(host) && !mine(owner)) throw new GameError('not_found', { what: 'town' }); const have = U.stationedOf(db, host.id, owner.id); let take = units && Object.keys(units).length ? U.cleanUnits(units) : have; take = Object.fromEntries(Object.entries(take).filter(([, n]) => n > 0)); if (U.isEmpty(take)) throw new GameError('not_enough_units', { reason: 'nothing stationed' }); for (const k of Object.keys(take)) if ((have[k] || 0) < take[k]) throw new GameError('not_enough_units', { unit: k, have: have[k] || 0, want: take[k] }); const hostTown = require('../state').loadTown(db, host.id); settle(db, hostTown, now); // the host's draw changes U.removeStationed(db, host.id, owner.id, take); P.reschedule(ctx, host.id, now); const mv = M.launchReturn(ctx, { worldId: host.world_id, ownerId: owner.owner_id, fromTownId: host.id, at: { x: host.x, y: host.y }, to: owner, units: take, cargo: {}, extra: { withdrawn: true } }); if (!mine(owner)) { const uid = U.userOfOperator(db, owner.owner_id); if (uid) ctx.notify(uid, host.world_id, 'reinforcements_sent_home', { hostTownId: host.id, ownerTownId: owner.id, units: take }); } return { movementId: mv.id, units: take, arriveAt: mv.arriveAt }; };