import { fetchAllTopics, fetchVideosByTopic } from '../utils/api';
import { APIError } from './errors';
import { getItem, setItem } from '../utils/safe-storage';
import getRandomTopic from '../utils/get-random-topic';
import { addVideosToState } from './videos';
import { 
  START_LOADING_ALL_TOPICS, 
  LOADED_ALL_TOPICS,
  START_LOADING_RANDOM_TOPIC,
  LOADED_RANDOM_TOPIC
} from './action_types';

export function getAllTopics() {
  return dispatch => {
    dispatch(startLoadingAllTopics());
    // this calls the API
    fetchAllTopics()
      .then(topics => {
        dispatch(loadedTopics(topics));
      }).catch(error => {
        dispatch(APIError(error));
      })
  };
};

function startLoadingAllTopics() {
  return {
    type: START_LOADING_ALL_TOPICS
  };
};

function loadedTopics(topics) {
  // cache
  setItem('allTopics', JSON.stringify(topics));
  setItem('topicsUpdatedAt', new Date());
  return {
    type: LOADED_ALL_TOPICS,
    payload: topics
  };
};
// actions :
// - async actions
// - simple: return action type and payload.
export function getRandomTopicVideos(allTopics, numVideos=4) {
  return dispatch => {
    const randomTopic = getRandomTopic(allTopics);
    dispatch(loadingRandomTopicVideos());
    fetchVideosByTopic(randomTopic.name, 0, 4)
      .then(videos => {
        dispatch(addVideosToState(videos));
        dispatch(loadedRandomTopicVideos(randomTopic, videos));
      });
  };
};

function loadedRandomTopicVideos(topic, videos) {
  return {
    type: LOADED_RANDOM_TOPIC,
    payload: {
      topic: topic,
      videos: videos
    }
  };
};

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