summaryrefslogtreecommitdiff
path: root/nodejs/automation/contracting.js
blob: 75bc96cdd2a672ef4153edb70ee3de7ac9cd6030 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import * as mining from './mining.js';
import * as dbContracts from '../database/contracts.js';
import * as dbShips from '../database/ships.js';
import * as api from '../lib/api.js';
import * as contracts from '../lib/contracts.js';
import * as libShips from '../lib/ships.js';
import * as systems from '../lib/systems.js';
import * as utils from '../lib/utils.js';

export async function init() {
	const cs = dbContracts.getContracts();
	cs.forEach(contract => run(contract));
}

async function run(contract) {
	await contracts.accept({id: contract.id});
	const contractSystem = utils.systemFromWaypoint(contract.terms.deliver[0].destinationSymbol);
	let ships = dbShips.getShipsAt(contractSystem);
	ships = ships.filter(ship => ship.registration.role !== 'SATELLITE'); // filter out probes

	switch(contract.type) {
	case 'PROCUREMENT':
		await runProcurement(contract, ships);
		break;
	default:
		throw `Handling of contract type ${contract.type} is not implemented yet`;
	}
}

async function runProcurement(contract, ships) {
	// TODO check if contract is fulfilled!
	const wantedCargo = contract.terms.deliver[0].tradeSymbol;
	const deliveryPoint = contract.terms.deliver[0].destinationSymbol;
	const asteroids = await systems.type({symbol: ships[0].nav.systemSymbol, type: 'ENGINEERED_ASTEROID'});
	const asteroidSymbol = asteroids[0].symbol;
	ships.forEach(async function(ship) {
		while (!dbContracts.getContract(contract.id).fulfilled) {
			ship = dbShips.getShip(ship.symbol);
			let goodCargo = ship.cargo.inventory.filter(i => i.symbol === wantedCargo)[0];
			// If we are in transit, we wait until we arrive
			const delay = new Date(ship.nav.route.arrival) - new Date();
			if (delay > 0) await api.sleep(delay);
			// Then it depends on where we are
			switch (ship.nav.waypointSymbol) {
			case asteroidSymbol:
				let response = await mining.mineUntilFullOf({
					good: wantedCargo,
					symbol: ship.symbol
				});
				await libShips.navigate({symbol: ship.symbol, waypoint: deliveryPoint});
				break;
			case deliveryPoint:
				if (goodCargo !== undefined) { // we could be here if a client restart happens right after selling before we navigate away
					console.log(`delivering ${goodCargo.units} of ${wantedCargo}`);
					if (await contracts.deliver({id: contract.id, symbol: ship.symbol, good: wantedCargo, units: goodCargo.units })) {
						break;
					}
				}
				await libShips.navigate({symbol: ship.symbol, waypoint: asteroidSymbol});
				break;
			default:
				await libShips.navigate({symbol: ship.symbol, waypoint: asteroidSymbol});
			}
		}
		// TODO repurpose the ship
	});
}