import axios from 'axios'
import Country from '../dto/Country'
import Region from '../dto/Region'
import Place from '../dto/Place'

class LocationService {
  countries: Country[] = []
  countriesPromise: Promise<Country[]> | null = null

  async getCountries(): Promise<Country[]> {
    if (this.countries.length) {
      return this.countries
    }

    if (this.countriesPromise !== null) {
      return this.countriesPromise
    }

    this.countriesPromise = axios
      .get('https://postcalc.s25.work/geo/countries')
      .then(response => {
        this.countries = response.data

        return this.countries
      })

    return this.countriesPromise
  }

  async getRegions(countryId: number, term: string): Promise<Region[]> {
    return axios
      .get('https://postcalc.s25.work/geo/state', {
        params: { countryId, term },
      })
      .then(response => response.data)
  }

  async searchPlaces(countryId: number, term: string): Promise<Place[]> {
    return axios
      .get('https://postcalc.s25.work/geo/search', {
        params: { countryId, term },
      })
      .then(response => response.data)
  }
}

export default new LocationService()
