/* global i18n */

import Controller from 'ember-controller';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';

const LOW = 'low';
const MEDIUM = 'medium';
const HIGH = 'high';
const SOURCE = 'source';

const SAVE_FAILURE = i18n('Oops, something went wrong. Please try again.');
const SAVE_SUCCESS = i18n('Video Restriction Changes Are Saved');

export default Controller.extend({
  notify: injectService(),

  selectedMaxBitrate: computed.alias('model.availableTranscode'),

  sourceRestricted: computed('selectedMaxBitrate', function () {
    return [LOW, MEDIUM, HIGH].includes(this.get('selectedMaxBitrate'));
  }),

  highRestricted: computed('selectedMaxBitrate', function () {
    return [LOW, MEDIUM].includes(this.get('selectedMaxBitrate'));
  }),

  subonlyArchivesLocal: computed.alias('model.subonlyArchives'),

  isSaving: false,

  save() {
    if (this.get('isSaving')) { return; }

    let notify = this.get('notify');

    this.set('isSaving', true);

    return this.get('model').save().then(() => {
      if (this.isDestroyed) { return; }

      notify.success(SAVE_SUCCESS);
    }, () => {
      if (this.isDestroyed) { return; }

      notify.error(SAVE_FAILURE);
    }).finally(() => {
      if (this.isDestroyed) { return; }

      this.set('isSaving', false);
    });
  },

  actions: {
    sourceRestrictionToggle() {
      this.set('selectedMaxBitrate', this.get('sourceRestricted') ? SOURCE : HIGH);
    },

    highRestrictionToggle() {
      this.set('selectedMaxBitrate', this.get('highRestricted') ? HIGH : MEDIUM);
    }
  }
});
