From 6facc3eb600da238212e3dc74bb95cc963b90f4c Mon Sep 17 00:00:00 2001
From: Hugo SUBTIL <ext.sopra.husubtil@grandlyon.com>
Date: Mon, 26 Oct 2020 11:19:44 +0100
Subject: [PATCH] feat: move location call upper for distance filtering

---
 package.json                                  |  1 +
 src/app/home/home.component.ts                | 53 ++++++++++++++++---
 src/app/models/structure.model.ts             |  1 +
 src/app/services/geojson.service.spec.ts      |  2 -
 .../components/card/card.component.html       |  2 +-
 .../components/card/card.component.ts         | 35 +++---------
 .../structure-list.component.html             |  2 +-
 .../structure-list.component.spec.ts          |  1 -
 8 files changed, 57 insertions(+), 40 deletions(-)

diff --git a/package.json b/package.json
index 4b09a880a..8c71c182f 100644
--- a/package.json
+++ b/package.json
@@ -31,6 +31,7 @@
     "json-server": "^0.16.2",
     "leaflet": "^1.7.1",
     "leaflet.locatecontrol": "^0.72.0",
+    "lodash": "^4.17.20",
     "luxon": "^1.25.0",
     "rxjs": "~6.6.0",
     "tslib": "^2.0.0",
diff --git a/src/app/home/home.component.ts b/src/app/home/home.component.ts
index ddf4ebc84..f50fd05b3 100644
--- a/src/app/home/home.component.ts
+++ b/src/app/home/home.component.ts
@@ -1,9 +1,12 @@
 import { Component, OnInit } from '@angular/core';
+import { Observable } from 'rxjs';
+import { mergeMap } from 'rxjs/operators';
+const { DateTime } = require('luxon');
+import * as _ from 'lodash';
 import { Structure } from '../models/structure.model';
 import { StructureService } from '../services/structure-list.service';
 import { GeoJson } from '../map/models/geojson.model';
 import { GeojsonService } from '../services/geojson.service';
-const { DateTime } = require('luxon');
 
 @Component({
   selector: 'app-home',
@@ -14,23 +17,59 @@ export class HomeComponent implements OnInit {
   public structures: Structure[] = [];
   public geolocation = false;
   public currentLocation: GeoJson;
-  constructor(private structureService: StructureService, private geojsonService: GeojsonService) {}
+  constructor(private structureService: StructureService, private geoJsonService: GeojsonService) {}
 
   ngOnInit(): void {
-    this.getStructures();
     if (navigator.geolocation) {
       this.getLocation();
     }
+    this.getStructures();
   }
 
   public getStructures(): void {
     this.structureService.getStructures().subscribe((structures) => {
-      this.structures = structures.map((structure) =>
-        this.structureService.updateOpeningStructure(structure, DateTime.local())
-      );
+      Promise.all(
+        structures.map((structure) => {
+          if (this.geolocation) {
+            return this.getStructurePosition(structure).then((val) => {
+              return this.structureService.updateOpeningStructure(val, DateTime.local());
+            });
+          } else {
+            return this.structureService.updateOpeningStructure(structure, DateTime.local());
+          }
+        })
+      ).then((structureList) => {
+        this.structures = _.sortBy(structureList, ['distance']);
+      });
     });
   }
 
+  /**
+   * Get structures positions and add marker corresponding to those positons on the map
+   */
+  private getStructurePosition(structure: Structure): Promise<Structure> {
+    return new Promise((resolve, reject) => {
+      this.getCoord(structure.voie).subscribe((coord: GeoJson) => {
+        structure.distance = this.geoJsonService.getDistance(
+          coord.geometry.getLon(),
+          coord.geometry.getLat(),
+          this.currentLocation.geometry.getLon(),
+          this.currentLocation.geometry.getLat(),
+          'M'
+        );
+        resolve(structure);
+      });
+    });
+  }
+
+  /**
+   * Get coord with a street reference
+   * @param idVoie Street reference
+   */
+  public getCoord(idVoie: number): Observable<GeoJson> {
+    return this.geoJsonService.getAddressByIdVoie(idVoie).pipe(mergeMap((res) => this.geoJsonService.getCoord(res)));
+  }
+
   public getLocation(): void {
     navigator.geolocation.getCurrentPosition((position) => {
       this.geolocation = true;
@@ -41,7 +80,7 @@ export class HomeComponent implements OnInit {
   }
 
   private getAddress(longitude: number, latitude: number): void {
-    this.geojsonService.getAddressByCoord(longitude, latitude).subscribe(
+    this.geoJsonService.getAddressByCoord(longitude, latitude).subscribe(
       (location) => (this.currentLocation = location),
       (err) => console.error(err)
     );
diff --git a/src/app/models/structure.model.ts b/src/app/models/structure.model.ts
index 191917321..278f117d7 100644
--- a/src/app/models/structure.model.ts
+++ b/src/app/models/structure.model.ts
@@ -31,6 +31,7 @@ export class Structure {
   public hours: Week;
   public isOpen: boolean;
   public openedOn: OpeningDay;
+  public distance?: string;
 
   constructor(obj?: any) {
     Object.assign(this, obj, {
diff --git a/src/app/services/geojson.service.spec.ts b/src/app/services/geojson.service.spec.ts
index 8695016a7..f6b6c9bda 100644
--- a/src/app/services/geojson.service.spec.ts
+++ b/src/app/services/geojson.service.spec.ts
@@ -31,7 +31,6 @@ describe('GeojsonService', () => {
           resolve();
         },
         (err) => {
-          console.log(err);
           resolve();
         }
       );
@@ -47,7 +46,6 @@ describe('GeojsonService', () => {
           resolve();
         },
         (err) => {
-          console.log(err);
           resolve();
         }
       );
diff --git a/src/app/structure-list/components/card/card.component.html b/src/app/structure-list/components/card/card.component.html
index 53f6dbb02..daf64b16c 100644
--- a/src/app/structure-list/components/card/card.component.html
+++ b/src/app/structure-list/components/card/card.component.html
@@ -3,7 +3,7 @@
 
   <div class="headerStructure" fxLayout="row" fxLayoutAlign="space-between center">
     <span class="typeStructure">{{ structure.typeDeStructure }}</span>
-    <span *ngIf="geolocation" class="distanceStructure">├─┤ {{ distance }}</span>
+    <span *ngIf="structure.distance" class="distanceStructure">├─┤ {{ this.formatDistance() }}</span>
   </div>
   <br />
   <div class="statusStructure" fxLayout="row" fxLayoutAlign="start center">
diff --git a/src/app/structure-list/components/card/card.component.ts b/src/app/structure-list/components/card/card.component.ts
index 1448989d5..0b93efe9e 100644
--- a/src/app/structure-list/components/card/card.component.ts
+++ b/src/app/structure-list/components/card/card.component.ts
@@ -1,4 +1,4 @@
-import { Component, Input, OnInit, OnChanges, SimpleChanges } from '@angular/core';
+import { Component, Input, OnInit } from '@angular/core';
 import { Structure } from '../../../models/structure.model';
 import { GeojsonService } from '../../../services/geojson.service';
 import { GeoJson } from '../../../map/models/geojson.model';
@@ -10,41 +10,20 @@ import { mergeMap } from 'rxjs/operators';
   templateUrl: './card.component.html',
   styleUrls: ['./card.component.scss'],
 })
-export class CardComponent implements OnInit, OnChanges {
+export class CardComponent implements OnInit {
   @Input() public structure: Structure;
-  @Input() public geolocation: GeoJson;
-  public distance: string;
 
   constructor(private geoJsonService: GeojsonService) {}
   ngOnInit(): void {}
 
-  ngOnChanges(changes: SimpleChanges): void {
-    if (changes.geolocation.currentValue) {
-      this.getStructurePosition();
-    }
-  }
-
   /**
-   * Get structures positions and add marker corresponding to those positons on the map
+   * Display distance in m or km according to value
    */
-  private getStructurePosition(): void {
-    this.getCoord(this.structure.voie).subscribe((coord: GeoJson) => {
-      this.distance = this.geoJsonService.getDistance(
-        coord.geometry.getLon(),
-        coord.geometry.getLat(),
-        this.geolocation.geometry.getLon(),
-        this.geolocation.geometry.getLat(),
-        'M'
-      );
-      this.formatDistance();
-    });
-  }
-
-  private formatDistance(): void {
-    if (this.distance.length > 3) {
-      this.distance = (parseInt(this.distance, 10) / 1000).toFixed(1).toString() + ' km';
+  public formatDistance(): string {
+    if (this.structure.distance.length > 3) {
+      return (parseInt(this.structure.distance, 10) / 1000).toFixed(1).toString() + ' km';
     } else {
-      this.distance += ' m';
+      return this.structure.distance + ' m';
     }
   }
 
diff --git a/src/app/structure-list/structure-list.component.html b/src/app/structure-list/structure-list.component.html
index 843ba1f55..017b98518 100644
--- a/src/app/structure-list/structure-list.component.html
+++ b/src/app/structure-list/structure-list.component.html
@@ -1,3 +1,3 @@
 <app-recherche></app-recherche>
 <span class="nbStructuresLabel">{{ structureList.length }} structures</span>
-<app-card *ngFor="let structure of structureList" [structure]="structure" [geolocation]="location"></app-card>
+<app-card *ngFor="let structure of structureList" [structure]="structure"></app-card>
diff --git a/src/app/structure-list/structure-list.component.spec.ts b/src/app/structure-list/structure-list.component.spec.ts
index b00f05ee5..ea045c551 100644
--- a/src/app/structure-list/structure-list.component.spec.ts
+++ b/src/app/structure-list/structure-list.component.spec.ts
@@ -163,7 +163,6 @@ describe('StructureListComponent', () => {
       })
     );
     structureList.length = 4;
-    console.log(structureList.length);
     component.structureList = structureList;
     fixture.detectChanges(); // calls NgOnit
   });
-- 
GitLab