'use strict'; /* POST /movements/:id/recall. Within the first 90 s (MILITARY.recallWindowMs) an outbound movement can turn around: * its arrive event is cancelled and a return leg takes the same units and cargo home in as long as they were out. */ const D = require('../../public/js/data.js'); const { GameError } = require('../errors'); const ctxOf = require('../military/ctx'); const U = require('../military/units'); const M = require('../military/movements'); module.exports = function recallMovement(ctx0, { userId, movementId }) { const ctx = ctxOf(ctx0); const { db, now } = ctx; const mv = M.getMovement(db, movementId); const op = mv && db.get('SELECT id FROM operators WHERE id = ? AND user_id = ?', mv.ownerId, userId); if (!mv || !op) throw new GameError('not_found', { what: 'movement' }); if (mv.status !== 'out' || mv.type === 'return') throw new GameError('conflict', { what: 'movement cannot be recalled', status: mv.status, type: mv.type }); if (now - mv.departAt > D.MILITARY.recallWindowMs) throw new GameError('recall_expired', { departAt: mv.departAt, windowMs: D.MILITARY.recallWindowMs }); const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null; const dest = U.homeTownFor(db, mv.ownerId, origin && origin.owner_id === mv.ownerId ? origin.id : null); if (!dest) throw new GameError('conflict', { what: 'no POP to return to' }); db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", now, mv.eventId); db.run("UPDATE movements SET status = 'recalled' WHERE id = ?", mv.id); const elapsed = Math.max(1000, now - mv.departAt); const f = Math.min(1, (now - mv.departAt) / Math.max(1, mv.arriveAt - mv.departAt)); const at = { x: Math.round(mv.from.x + (mv.to.x - mv.from.x) * f), y: Math.round(mv.from.y + (mv.to.y - mv.from.y) * f) }; const extra = Object.assign({}, mv.extra, { recalled: true }); if (mv.type === 'transport') extra.link = 1; const ret = M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: null, at, to: dest, units: mv.units, cargo: mv.cargo, arriveAt: now + elapsed, parentId: mv.id, extra }); return { recalled: mv.id, returnMovementId: ret.id, arriveAt: ret.arriveAt }; };