import firebase from 'firebase';
import { config } from '../firebaseConfig';
import { combineReducers } from 'redux';
import { refreshState } from '../actions/index';
import axios from 'axios';
import store from '../store/index';

var app = firebase.initializeApp(config);
var database = app.database().ref().child('tests');

database.on('value', snap => {
  var databaseTests = [];
  var retrievedObject = snap.val();
  if(retrievedObject){
    var keys = Object.keys(retrievedObject);
    for (var i = 0; i < keys.length; i++) {
      databaseTests[i] = retrievedObject[keys[i]];
    }
  }
  setTimeout(()=>{store.dispatch({type: 'REFRESH_STATE', databaseTests})},500)

})

// axios.get('https://react-project-a3c86.firebaseio.com/tests.json').then(function(result){
//   var retrievedObject = result.data;
//   if(retrievedObject){
//     var keys = Object.keys(retrievedObject);
//     for (var i = 0; i < keys.length; i++) {
//       databaseTests[i] = retrievedObject[keys[i]];
//     }
//   }
// })

const addTestReducer = (state = [], action) => {
  if( action.type === 'ADD_NEW_TEST'){
    database.push().set(action.testObject);
    return state //.concat(action.testObject);
  }
  else if(action.type === 'REFRESH_STATE'){
    return action.databaseTests;
  }
  return state;
}

// const refreshStore = (state = databaseTests, action) => {
//   if( action.type === 'REFRESH_STATE'){
//     return action.snap
//   }
//   return state;
// }

// export default combineReducers({
//    addTestReducer,
//    refreshStore
// })

export default addTestReducer;
