import config from '../config';
import { START_LOADING_VIDEOS, RECEIVE_VIDEOS } from './action_types';

function fetchVideos() {
  console.log('fetchVideos called');
  return dispatch => {
    console.log('inside dispatch function');
    dispatch(startLoadingVideos());
    const params = {
      "keys":["editable","modified","title","source","project","topic","language","duration","id"],
      "query": {
        "conditions":[],
        "operator":"&"
      },
      "range":[0,100],
      "sort": [{"key":"title","operator":"+"}]
    };
    let formData = new FormData();
    formData.append('action', 'find');
    formData.append('data', JSON.stringify(params));
    fetch(config.apiUrl, {
      method: 'POST',
      // headers: {
      //   "Content-Type": "application/x-www-form-urlencoded"
      // },
      body: formData
    })
    .then(response => response.json())
    .then(json => {
      dispatch(receiveVideos(json.data.items));
    });

  }
}

function startLoadingVideos() {
  return {
    type: START_LOADING_VIDEOS
  }
}

function receiveVideos(videos) {
  return {
    type: RECEIVE_VIDEOS,
    payload: videos
  }
}

export default fetchVideos;