// import { delay } from 'redux-saga';
import { put, takeEvery, all, call, select } from 'redux-saga/effects';

// resource
import auth from 'store/auth';
import app from 'store/app';
import { loadContent } from 'store/content/sagas';
import { config } from 'config/general';

// import { onAuthStateChanged } from 'store/utils/firebase';

import { userInit } from 'store/account/sagas';

export function* bootup(): void {
  yield put(app.actions.loader.show.action());

  const apiCalls = [];
  apiCalls.push(call(loadContent));

  const session = yield select(auth.selectors.getSession);

  if (session) {
    // load user
    apiCalls.push(call(userInit));
  }

  yield all(apiCalls);

  /*
  if (config.firebase) {
    const waitFirebaseAuth = yield call(onAuthStateChanged);
    // console.log('Firebase auth status', waitFirebaseAuth);
    // This is where you wait for a callback from firebase (either null or the user)
    // const channel = yield call(getAuthChannel);
    // yield take(channel);
  }  
  */

  yield put(app.actions.bootup.result.action());
  yield put(app.actions.loader.hide.action());
}

function* bootupWatcher(): void {
  yield all([yield takeEvery(app.actions.bootup.request.constant, bootup)]);
}

export default function* saga(): void {
  yield call(bootupWatcher);
}
