occupancy-dataset.pipe.ts 1.98 KB
Newer Older
Léonard Treille's avatar
Léonard Treille committed
1
2
3
4
5
import { Pipe, PipeTransform } from '@angular/core';
import { OccupancyService } from './occupancy.service';
import { Dataset, Axis } from '@components/chart/chart.model';
import { NextStop } from '@features/realtime-data/realtime-data.model';
import { Observable } from 'rxjs';
Léonard Treille's avatar
Léonard Treille committed
6
7
8
9
10
11
12
13
14
15
16
import { StopOccupancy } from './occupancy.model';

const fakeResponse: StopOccupancy = {
	timeSlots: ['00:00', '06:45', '08:45', '11:30', '13:30', '15:30', '18:30', '21:00'],
	currentTimeSlot: 5,
	occupancy: {
		routeDirection: {
			'SEM:C:1': [156, 2825, 1800, 1121, 1349, 2255, 944, 420]
		}
	}
};
Léonard Treille's avatar
Léonard Treille committed
17
18
19
20
21
22
23
24
25
26
27

@Pipe({
	name: 'occupancyDataset'
})
export class OccupancyDatasetPipe implements PipeTransform {

	constructor(private occupancyService: OccupancyService) { }

	transform(obj: NextStop, axis?: { x?: Axis, y?: Axis, }): Observable<Dataset> {
		const routeDirection = `${obj.ligne.id}:${obj.pattern.dir}`;
		return new Observable<Dataset>(observer => {
Léonard Treille's avatar
Léonard Treille committed
28
			observer.next(this.toDataset(fakeResponse, 'SEM:C:1', axis, true));
Léonard Treille's avatar
Léonard Treille committed
29
			this.occupancyService.getOccupancy(obj.stopId).subscribe(response => {
Léonard Treille's avatar
Léonard Treille committed
30
31
				const dataset = this.toDataset(response, routeDirection, axis, false);
				observer.next(dataset);
Léonard Treille's avatar
Léonard Treille committed
32
33
34
35
36
				observer.complete();
			});
		});
	}

Léonard Treille's avatar
Léonard Treille committed
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
68
69
70
71
72
	private toDataset(data: StopOccupancy, routeDirection: string, axis?: { x?: Axis, y?: Axis, }, ghost = false): Dataset {
		let dataset: Dataset;
		if (data?.occupancy?.routeDirection && routeDirection in data.occupancy.routeDirection) {
			const points = data.timeSlots.map((time, index, list) => {
				return {
					x: time,
					y: data.occupancy.routeDirection[routeDirection][index]
				};
			});
			const isEmpty = points.every(p => p.y === 0);
			dataset = {
				points: [[]],
				axis,
				options: {
					padding: [4, 0, 8, 16],
					empty: isEmpty,
					ghost
				}
			};
			if (!isEmpty) {
				dataset.points = [points];
			}
		} else {
			dataset = {
				points: [[]],
				axis,
				options: {
					padding: [4, 0, 8, 16],
					unavailable: true,
					ghost
				}
			}
		}
		return dataset;
	}

Léonard Treille's avatar
Léonard Treille committed
73
}