import { ApisauceInstance, create } from 'apisauce'
import Api from './api'
import { ApiConfig, DEFAULT_GOOGLE_API_CONFIG } from './api.config'
import config from 'config'

export default class GoogleApi extends Api {
  api: ApisauceInstance

  constructor(apiConfig: ApiConfig = DEFAULT_GOOGLE_API_CONFIG) {
    super(apiConfig)

    this.api = create({
      baseURL: apiConfig.url,
      timeout: apiConfig.timeout,
      params: {
        key: config.google.apiKey
      }
    })
  }

  async getFonts(): Promise<{ name: string; url: string }[]> {
    const response = await this.api.get<{
      items: {
        family: string
        files: {
          regular?: string
        }
      }[]
    }>('/webfonts/v1/webfonts')

    const data = response.data
    if (!data) {
      return []
    }

    return data.items
      .filter(x => x.files.regular)
      .map(x => ({
        name: x.family,
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        url: x.files.regular!
      }))
  }
}
