/* globals i18n */

import RSVP from 'rsvp';
import Service from 'ember-service';
import injectService from 'ember-service/inject';
import {
  CLAIM_OFFER_KEY as claimOfferKey
} from 'web-client/utilities/samus/prime-tracking-keys';

const { Promise } = RSVP;

export default Service.extend({
  api: injectService(),
  notify: injectService(),
  session: injectService(),
  tracking: injectService(),

  offerIdToCode: {},

  claim(offerId){
    return new Promise((resolve, reject) => {
      let { isAuthenticated, userData } = this.get('session');
      if (!isAuthenticated) {
        return reject();
      }

      let trackingPayload = {
        time: Date.now(),
        offerId: offerId,
        userData: userData
      };

      this.get('tracking').trackEvent({ event: claimOfferKey, data: trackingPayload });

      let url = `/api/premium/offers/${offerId}/claim`;

      this.get('api').request('post', url, trackingPayload)
        .then(data => {
          return resolve(data);
        })
        .catch(error => {
          if (error.status && error.status >= 400) {
            let errorMessage = i18n('Sorry, there was an error retrieving your content');
            this.get('notify').error(errorMessage);
            return reject(error);
          }
          throw error;
      });
    });
  }
});
