import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { switchMap } from 'rxjs';
import { environment } from '../../environments/environment';
import { AutocompleteService } from './auto-complete.service';
import { Pin } from '../model/Pin';

@Injectable({
  providedIn: 'root',
})
export class PinService {
  allPins: Pin[] = [];
  filteredPins: Pin[] = [];

  private apiURL = environment.apiURL;

  constructor(
    private http: HttpClient,
    private autoCompleteService: AutocompleteService
  ) {}

  getPins(): any {
    const url = `${this.apiURL}/pins`;
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + localStorage.getItem('auth_token'),
    });
    return this.http.get<any>(url, { headers });
  }

  addPin(pin: {
    title: string;
    description: string;
    location: string;
    files: any[];
  }) {
    const url = `${this.apiURL}/pin/add`;
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + localStorage.getItem('auth_token'),
    });
    return this.autoCompleteService.getAdressCoordinates(pin.location).pipe(
      switchMap((response: any) => {
        const coords: [string, string] = [response[0].lat, response[0].lon];
        return this.http.post<any>(
          url,
          {
            title: pin.title,
            description: pin.description,
            location: coords,
            files: pin.files,
            user_id: '',
          },
          { headers }
        );
      })
    );
  }
}
