import EmberObject from 'ember-object';
import injectService from 'ember-service/inject';
import RSVP from 'rsvp';
import { normalizeVideoId } from 'web-client/utilities/normalize-video-id';

function serializeAppeal(appeal) {
  let serializedAppeal = {};
  Object.keys(appeal).forEach(function (key) {
    return serializedAppeal[key.camelize()] = appeal[key];
  });

  return serializedAppeal;
}

const VodAppeal = EmberObject.extend({
  isInitialized: false,
  getFromAPI: true,
  vodAppealsService: injectService('vod-appeals'),

  initializeVodAppeal(vodId) {
    if (!this.get('getFromAPI')) {
      return;
    }

    this.set('vodId', vodId);

    this.get('vodAppealsService').getVodAppeal(vodId).then((appeal) => {
      if (this.isDestroyed) { return; }
      this.setProperties(serializeAppeal(appeal));
      this.set('isInitialized', true);
    });
  },

  submitAppeal(formData) {
    if (!this.get('isInitialized')) {
      return RSVP.reject();
    }

    return this.get('vodAppealsService').createAppeal(this.get('vodId'), formData).then(() => {
      if (this.isDestroyed) { return; }
      this.set('canCreateAppeal', false);
      this.set('canViewAppeal', true);
      this.set('hasPendingAppeal', true);
    });
  }
});

let _cache = {};

VodAppeal.reopenClass({

  // Input: vod id. Do not call on non HLS vod ids.
  find(owner, id) {
    id = normalizeVideoId(id);
    if (!_cache[id]) {
      let appeal = owner.lookup('model:vod-appeal');
      appeal.initializeVodAppeal(id);
      _cache[id] = appeal;
    }
    return _cache[id];
  },

  resetCache() {
    Object.keys(_cache).forEach(key => {
      let item = _cache[key];
      if (!item.isDestroyed) {
        _cache[key].destroy();
      }
    });
    _cache = {};
  }
});

export default VodAppeal;
