wanjingy.github.io / hw8 / frontend / src / app / search-form / search-form.component.ts
search-form.component.ts
Raw
import { Component, EventEmitter, Output } from '@angular/core';
import { FormControl } from '@angular/forms';
import { FormBuilder } from '@angular/forms';
import { debounceTime, finalize, lastValueFrom, Observable, switchMap, tap } from 'rxjs';
import { SearchFormService } from '../search-form.service'
import { Event } from '../event';

@Component({
  selector: 'app-search-form',
  templateUrl: './search-form.component.html',
  styleUrls: ['./search-form.component.css']
})
export class SearchFormComponent {
  constructor(
    private formBuilder: FormBuilder,
    private searchFormService: SearchFormService
  ){}
  searchForm = this.formBuilder.group({
    keyword: new FormControl(''),
    distance: new FormControl(10),
    category: new FormControl('default'),
    location: new FormControl(''),
    isAuto: new FormControl(false)
  });
  isAutoFillLoading: boolean = false;
  filteredAutoFills: string[] = [];

  events: Event[] = [];
  @Output() messageEvents = new EventEmitter<Event[]>();
  @Output() messageClear = new EventEmitter<void>();

  searchQuery = {
    keyword: '',
    distance: 10,
    category: 'default',
    lat: 0,
    lng: 0
  };
  ngOnInit(){
    this.searchForm.controls.keyword.valueChanges
      .pipe(
        debounceTime(1000),
        tap(()=>(this.isAutoFillLoading = true)),
        switchMap((value) => 
          this.searchFormService
            .getAutoFill(value)
            .pipe(finalize(() => (this.isAutoFillLoading = false)))
        )
      ).subscribe((autofills) => (this.filteredAutoFills = autofills));
  }
  isAutoOnChange(): void{
    if(this.searchForm.value.isAuto){
      this.searchForm.controls.location.disable();
      this.searchForm.controls.location.setValue('');
    }else{
      this.searchForm.controls.location.enable();
    }
  }
  async onSubmit(): Promise<void>{
    this.searchQuery.keyword = (this.searchForm.value.keyword != null && this.searchForm.value.keyword != undefined) ? this.searchForm.value.keyword : '';
    this.searchQuery.distance = (this.searchForm.value.distance != null && this.searchForm.value.distance != undefined) ? this.searchForm.value.distance : 10;
    this.searchQuery.category = (this.searchForm.value.category != null && this.searchForm.value.category != undefined) ? this.searchForm.value.category : 'default';
    if(this.searchForm.value.isAuto){
      const ipLocation = await lastValueFrom(this.searchFormService.getIPLocation());
        // .subscribe((ipLoation) => {
        //   var locs = ipLoation.split(',');
        //   this.searchQuery.lat = parseFloat(locs[0]);
        //   this.searchQuery.lng = parseFloat(locs[1]);
        // })
        if(!ipLocation || ipLocation == ''){
          this.messageEvents.emit([]);
          return;
        }else{
          var locs = ipLocation.split(',');
          this.searchQuery.lat = parseFloat(locs[0]);
          this.searchQuery.lng = parseFloat(locs[1]);   
        }
    }else{
      const location = await lastValueFrom(this.searchFormService.getGoogleLocation(this.searchForm.value.location))
          // .subscribe((location) =>{
          //   this.searchQuery.lat = location.lat;
          //   this.searchQuery.lng = location.lng;
          // })
      if(location){
        this.searchQuery.lat = location.lat;
        this.searchQuery.lng = location.lng;
      }else{
        this.messageEvents.emit([]);
        return;
      }
    }
    this.events = await lastValueFrom(this.searchFormService.getEvents(this.searchQuery)) as Event[];
      // .subscribe((events) => (console.log(events)))
    this.events.sort((a, b) => (a.date + ' ' + a.time < b.date+ ' ' + b.time) ? -1 : 1)
    this.messageEvents.emit(this.events);
  }
  clear(): void{
    this.searchForm.reset({distance: 10, category: 'default'});
    this.searchForm.controls.location.enable();
    this.messageClear.emit();
  }
}