import { fetchPlaces, fetchVideosByPlace } from '../utils/api';
import { APIError } from './errors';
import { getItem, setItem } from '../utils/safe-storage';
import getRandomTopic from '../utils/get-random-place';
import { addVideosToState } from './videos';
import { 
  START_LOADING_ALL_PLACES, 
  LOADED_ALL_PLACES,
  START_LOADING_RANDOM_PLACE,
  LOADED_RANDOM_PLACE
} from './action_types';

export function getAllPlaces() {
  return dispatch => {
    dispatch(startLoadingAllPlaces());
    // this calls the API
    fetchPlaces()
      .then(places => {
        dispatch(loadedPlaces(places));
      }).catch(error => {
        dispatch(APIError(error));
      })
  };
};

function startLoadingAllPlaces() {
  return {
    type: START_LOADING_ALL_PLACES
  };
};

function loadedPlaces(places) {
  // cache
  setItem('allPlaces', JSON.stringify(places));
  setItem('placesUpdatedAt', new Date());
  return {
    type: LOADED_ALL_PLACES,
    payload: places
  };
};
// actions :
// - async actions
// - simple: return action type and payload.
export function getRandomPlaceVideos(allPlaces, numVideos=3) {
  return dispatch => {
    const randomTopic = getRandomTopic(allPlaces);
    dispatch(loadingRandomTopicVideos());
    fetchVideosByPlace(randomTopic.name, 0, numVideos)
      .then(videos => {
        dispatch(addVideosToState(videos));
        dispatch(loadedRandomTopicVideos(randomTopic, videos));
      });
  };
};

function loadedRandomTopicVideos(place, videos) {
  return {
    type: LOADED_RANDOM_PLACE,
    payload: {
      place: place,
      videos: videos
    }
  };
};

function loadingRandomTopicVideos() {
  return {
    type: START_LOADING_RANDOM_PLACE
  };
};