import { observable, action, reaction } from 'mobx';

import storeCoords from 'stores/coords.js';

export default new class StoreSearch {
	
	dispose = 0
	
	@observable
	query = ''
	
	@observable
	type = 'stops'
	
	@observable.struct
	results = {
		stops: [],
		routes: []
	}
	
	startScanning() {
		
		this.dispose = reaction(() => ({
			lat: storeCoords.lat,
			lng: storeCoords.lng
		}), () => {
			if (!this.query) this.fetchResults();
		});
		
	}
	
	stopScanning() {
		this.dispose();
	}
	
	@action
	updateQuery(query) {
		this.query = query;
	}
	
	@action
	updateType(type) {
		this.type = type;
	}
	
	@action.bound
	async fetchResults() {
		const [ query, lat, lng ] = [ this.query, storeCoords.lat, storeCoords.lng ];
		const results = query || (lat && lng) ? await (await fetch(`${process.env['REACT_APP_API']}/search?${query ? `&query=${query}` : ''}${lat && lng ? `&lat=${lat}&lng=${lng}` : ''}`)).json() : {};
		this.results = results;
	}
	
};

@@ -270,16 +270,77 @@
 %5B%5D%0A%09%7D%0A%09%0A
+%09// Start fetching nearby search results on location update.%0A
 %09startSc
@@ -499,18 +499,105 @@
 %0A%09%09%7D
-);%0A%09%09%0A%09%7D%0A%09
+, %7B fireImmediately: true %7D);%0A%09%09%0A%09%7D%0A%09%0A%09// Stop fetching nearby search results on location update.
 %0A%09st
@@ -871,24 +871,75 @@
 ;%0A%09%09
-const results = 
+%0A%09%09// Return on manual search or if coordinates unavailable.%0A%09%09if (
 quer
@@ -947,22 +947,77 @@
  %7C%7C 
-(
+!
 lat 
-&& 
+%7C%7C !
 lng) 
-?
+return;%0A%09%09%0A%09%09// Fetch search results.%0A%09%09const results =
  awa
@@ -1164,17 +1164,25 @@
 on()
- : %7B%7D;%0A%09%09
+;%0A%09%09if (results) 
 this
@@ -1201,16 +1201,19 @@
 esults;%0A
+%09%09%0A
 %09%7D%0A%09%0A%7D;%0A

Fix nearby stops not loading