import injectService from 'ember-service/inject';
import { underscore } from 'ember-string';
import $ from 'jquery';

import ApplicationAdapter from './application';

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

  findRecord(store, type, id) {
    let api = this.get('api');
    let url = `/api/ticket_products/${ id }`;
    let getRequest = api.request('get', url);

    return getRequest.then(null, this._logFailure);
  },

  createRecord(store, type, snapshot) {
    let api = this.get('api');
    let url = `/api/ticket_products/${ snapshot.id }`;
    let payload = this._formatPayload(snapshot.attributes());
    let postRequest = api.request('post', url, payload);

    return postRequest.then(null, this._logFailure);
  },

  updateRecord(store, type, snapshot) {
    let api = this.get('api');
    let url = `/api/ticket_products/${ snapshot.id }`;
    let payload = this._formatPayload(snapshot.attributes());
    let putRequest = api.request('put', url, payload);

    return putRequest.then(null, this._logFailure);
  },

  _formatPayload(camelCaseAttributes) {
    let snakeCaseAttributes = {};

    Object.keys(camelCaseAttributes).forEach(camelCaseKey => {
      let attribute = camelCaseAttributes[camelCaseKey];

      if (typeof attribute !== 'undefined') {
        let snakeCaseKey = underscore(camelCaseKey);

        snakeCaseAttributes[snakeCaseKey] = attribute;
      }
    });

    // Format as a query string
    return $.param(snakeCaseAttributes);
  },

  _logFailure(failedReason) {
    throw failedReason;
  }
});
