import ApplicationAdapter from './application';
import injectService from 'ember-service/inject';
import RSVP from 'rsvp';
import { QUERY_DATA, EMPTY_QUERY_DATA } from 'web-client/utilities/onsite-notifications/data';
import nonce from 'web-client/utilities/nonce';

import urlParams from 'web-client/utilities/url-params';

let useTestData = urlParams.onsite_test_data === "1";
let testPagesLoaded = 0;

export default ApplicationAdapter.extend({
  api: injectService(),
  apiVersion: 5,
  session: injectService(),

  shouldReloadRecord() {
    return false;
  },

  shouldBackgroundReloadRecord() {
    return false;
  },

  findRecord(store, type, id) {
    let userId = this.get('session.userData.id');
    let url = `users/${userId}/notifications/onsite/${id}`;
    return this.authRequest(url);
  },

  query(store, type, query) {
    if (useTestData) {
      return this._generateTestData();
    }

    let userId = this.get('session.userData.id');
    let url = `users/${userId}/notifications/onsite`;
    return this.authRequest(url, 'get', query);
  },

  _generateTestData() {
    return new RSVP.Promise(function(resolve) {
      setTimeout(function() {
        if (++testPagesLoaded >= 5) {
          return resolve(EMPTY_QUERY_DATA);
        }

        let queryData = {
          cursor: QUERY_DATA.cursor,
          notifications: []
        };

        QUERY_DATA.notifications.forEach((data) => {
          let copy = Object.assign({}, data);
          copy.id = nonce();
          queryData.notifications.push(copy);
        });

        return resolve(queryData);
      }, 1000);
    });
  }
});
