initial commit
[browser-rts.git] / src / tasks / construction.ts
1 import { Task } from './task';
2 import { BuildQueueRepository } from '../repository/build-queue';
3 import { CityRepository } from '../repository/city';
4 import { BuildingRepository } from '../repository/buildings';
5 import { MailRepository } from '../repository/mail';
6
7
8 const buildQueueRepo = new BuildQueueRepository();
9 const cityRepo = new CityRepository();
10 const buildingRepo = new BuildingRepository();
11 const mailRepo = new MailRepository();
12
13 type Construction = {
14     id: string,
15     building_type: string,
16     created: number,
17     amount: number,
18     due: number,
19     owner: string
20 };
21
22 export const construction = new Task<Construction>('construction', async (task, job) => {
23     // validate that this is a real build queue item
24     const dbEntry = await buildQueueRepo.FindOne({id: job.data.id});
25
26     if(!dbEntry) {
27         console.error(`Build queue ${job.data.id} is invalid`);
28         return;
29     }
30
31     const building = await buildingRepo.findBySlug(dbEntry.building_type);
32     if(!building) {
33         console.error(`Building type ${job.data.building_type} is not valid`);
34         return;
35     }
36
37     // get the city!
38     const city = await cityRepo.getUsersCity(dbEntry.owner);
39
40     if(!city) {
41         console.error(`City for owner ${job.data.owner} does not exist`);
42         return;
43     }
44
45     // resource checks have already been done and resources have 
46     // been removed from the city. so we're good to just give them
47     // what they want.
48
49     city[dbEntry.building_type] += dbEntry.amount;
50
51     // lets update the city
52     await Promise.all([
53         cityRepo.save(city),
54         buildQueueRepo.Delete({id: dbEntry.id}),
55         mailRepo.createSystemMessage(
56             '-',
57             dbEntry.owner,
58             `Your ${building.display} (${dbEntry.amount}) were completed`,
59             `
60             <b>Congratulations!</b>
61             <p>The your people have toiled and constructed ${dbEntry.amount} ${building.display}!</p>
62             `
63         )
64     ]);
65 });