import axios from 'axios'
import { Movie } from './movie-wall';
import { Config } from '../App';

const tmdb = axios.create({
  baseURL: `https://api.themoviedb.org/3/movie`,
  headers: {
    Authorization: 'Bearer ' + import.meta.env.local.VITE_TOKEN,
    'Content-Type': 'application/json',
  }
})
export default {
  getMovie: async function({ language }: Config, id: number, setChosenMovie: Function) {
    let res = await tmdb.get("/" + id, {
      params: {
        language
      }
    })
    if (res.status == 200) {
      setChosenMovie(res.data)
    } else {
      throw Error("API call failed! Response: " + JSON.stringify(res))
    }
  },
  /**
* Calls tmdb API/popular and then fires the callback with res.data.results as argument
* @param {Function} callback
* @returns {boolean}
*/
  getPopular: async function({ language, region, page }: Config, callback: Function) {
    let res = await tmdb.get('/popular',
      {
        params: {
          language,
          region,
          page
        }
      })
    if (res.status === 200) {
      res = res.data.results
      callback(res)
      return true
    } else {
      throw Error("API call failed! Response: " + JSON.stringify(res))
    }
  },
  /**
   * Calls TMDB/similar, then fires the callback with res.data.results.unshift(movie) as argument
   */
  getSimilar: async function({ language, page }: Config, movie: Movie, setMovies: Function, setSimilarMoviesAvailable: Function) {
    let res = await tmdb.get(movie.id + '/similar', {
      params: {
        language,
        page
      }
    })
    if (res.status === 200) {
      const array: Array<Movie> = res.data.results
        .filter((e: Movie) => {
          return e.poster_path
        })
      if (array.length > 0) {
        setMovies(array)
        setSimilarMoviesAvailable(true)
      } else {
        setSimilarMoviesAvailable(false)
      }
      return true
    } else {
      throw Error("API call failed! Response: " + JSON.stringify(res))
    }

  },
  getWhereToWatch: async function(movie: Movie, setWatchProviders: Function, config: Config) {
    if (movie?.id) {
      let res = await tmdb.get(movie.id + "/watch/providers")
      if (res.status == 200) {
        setWatchProviders(res.data.results[config.locale])
      } else {
        throw Error("API call failed! Response: " + JSON.stringify(res))
      }
    }
  },
  makeBgImgUrl:
    /**
     * Returns a complete tmdb image url in large format
     */
    function(path: string) {
      return "https://image.tmdb.org/t/p/w1280" + path
    },
  makeImgUrl:
    /**
    * Returns a complete tmdb img url
#  */
    function(path: string) {
      return "https://image.tmdb.org/t/p/w500" + path
    },
  makeMovieLink:
    /**
    *
    */
    function(movie: Movie) {
      return "https://www.themoviedb.org/movie/" + movie.id
    },
  makeLogoPath: function(str: string) {
    return "https://image.tmdb.org/t/p/original/" + str
  }
}
