d5e47e6014401f4f1623665abaa24ca830553ef0
[browser-rts.git] / src / repository / army.ts
1 import { Repository } from "./base";
2 import { v4 as uuid } from 'uuid';
3 import { City } from "./city";
4
5 export type Army = {
6     soldiers: number;
7     attackers: number;
8     defenders: number;
9     sp_attackers: number;
10     sp_defenders: number;
11 }
12
13 export type ArmyQueue = {
14     id: string;
15     owner: string;
16     your_city: string;
17     created: number;
18     due: number;
19     attacked_city: string;
20 } & Army;
21
22 export type ArmyQueueWithAttackedOwner = {
23     attacked_account: string;
24     location_x: number;
25     location_y: number;
26 } & ArmyQueue;
27
28 export class ArmyRepository extends Repository<ArmyQueue> {
29     constructor() {
30         super('army_queue');
31     }
32
33     async create(owner: string, city: City, attacked_city: City, army: Army, distance: number): Promise<ArmyQueue> {
34         // figure out the distance to the attacked city
35
36         const info: ArmyQueue = {
37             id: uuid(),
38             owner: owner,
39             your_city: city.id,
40             attacked_city: attacked_city.id,
41             created: Date.now(),
42             due: (distance * 1000) + Date.now(),
43             ...army
44         };
45
46         await this.Insert(info);
47
48         return info
49     }
50
51     async listOutgoing(city_id: string): Promise<ArmyQueueWithAttackedOwner[]> {
52         return await (this.db.raw(`select 
53         aq.*, o.username as attacked_account, c.location_x, c.location_y
54         from army_queue aq
55         join cities c on c.id = aq.attacked_city 
56         join accounts o on o.id = c.owner 
57         order by due asc`)) as ArmyQueueWithAttackedOwner[];
58     }
59
60     async listIncoming(city_id: string): Promise<ArmyQueue[]> {
61         return this.FindAll({attacked_city: city_id});
62     }
63 }