import { City, Location, Path } from "../shared/map";
+import type { Player } from '../shared/player';
+import type { Travel } from '../shared/travel';
import { db } from './lib/db';
+import { random } from 'lodash';
export async function getAllServices(city_id: number): Promise<Location[]> {
return db.select('*')
.orderBy('display_order');
}
+export async function getService(serverId: number): Promise<Location> {
+ return db.select('*').first().from<Location>('locations').where({
+ id: serverId
+ });
+}
+
export async function getAllPaths(city_id: number): Promise<Path[]> {
const res = await db.raw(`
select
export async function getCityDetails(city_id: number): Promise<City> {
return db.first().select('*').from<City>('cities').where({id: city_id});
}
+
+export async function travel(player: Player, dest_id: number): Promise<Travel> {
+ const city = await getCityDetails(dest_id);
+ const path = await db.first().select('*').from('paths').where({
+ starting_city: player.city_id,
+ ending_city: dest_id
+ });
+ if(!city) {
+ throw new Error('Invalid destination city');
+ }
+ if(!path) {
+ throw new Error(`Invalid path ${player.city_id} => ${dest_id}`);
+ }
+
+ const deviation = Math.floor(path.distance * (random(3,10)/100));
+ const steps = random(path.distance - deviation, path.distance + deviation);
+
+ const rows = await db('travel').insert({
+ player_id: player.id,
+ source_id: player.city_id,
+ destination_id: dest_id,
+ total_distance: steps
+ }).returning('*');
+
+ if(rows.length !== 1) {
+ console.log(rows);
+ throw new Error('Unexpected response when creating travel');
+ }
+
+ return rows[0] as Travel;
+}
+
+export async function stepForward(player_id: string): Promise<Travel> {
+ const rows = await db('travel').increment('current_position').returning('*');
+
+ if(rows.length !== 1) {
+ console.log(rows);
+ throw new Error('Unexpected response when moving');
+ }
+
+ return rows[0] as Travel;
+}
+
+export async function clearTravelPlan(player_id: string): Promise<Travel> {
+ return completeTravel(player_id);
+}
+
+export async function completeTravel(player_id: string): Promise<Travel> {
+ const rows = await db('travel').where({player_id}).delete().returning('*');
+ if(rows.length !== 1) {
+ console.log(rows);
+ throw new Error('Unexpected response when moving');
+ }
+
+ return rows[0] as Travel;
+}
+
+export async function getTravelPlan(player_id: string): Promise<Travel> {
+ return db.select('*').first().from<Travel>('travel').where({
+ player_id
+ });
+}